flexicon.code package

Subpackages

Submodules

flexicon.code.BaseOperations module

class flexicon.code.BaseOperations.EnumerableWrapper(enumerable)[source]

Bases: object

Wraps C# IEnumerable to provide Pythonic interface.

C# IEnumerable collections don’t support indexing or .Count in Python. This wrapper makes them behave like Python sequences while maintaining lazy evaluation when possible.

Provides:
  • .Count property (returns count of items)

  • Indexing support ([0], [1:3], etc.)

  • Iteration support (for item in collection)

  • Contains support (x in collection)

Usage:

items = GetWordforms()  # Returns IEnumerable
count = items.Count      # ✅ Works (Pythonic!)
first = items[0]         # ✅ Works (indexing)
if "word" in items:      # ✅ Works (contains)
    ...
property Count

Get count of items in the collection (Pythonic for C# .Count).

Returns:

Number of items in the enumerable.

Return type:

int

Example:

items = project.GetWordforms()
count = items.Count  # Returns number of wordforms
class flexicon.code.BaseOperations.wrap_enumerable(func)[source]

Bases: object

Descriptor to automatically wrap IEnumerable return values.

Wraps methods that return C# IEnumerable collections to make them Pythonic with .Count property and indexing support.

Must be a descriptor to properly delegate to OperationsMethod’s __get__, ensuring the descriptor protocol works correctly when stacked decorators are used.

Usage:

class MyOperations(BaseOperations):
    @wrap_enumerable
    @OperationsMethod
    def GetAll(self):
        return self.project.GetAllItems()

    # Now users can do:
    items = GetAll(project)
    count = items.Count      # Works!
    first = items[0]         # Works!
class flexicon.code.BaseOperations.OperationsMethod(func)[source]

Bases: object

Descriptor enabling methods to work as both class and instance methods.

Allows calling operation methods in two ways:
  • Class level (no instantiation): POSOperations.GetAll(project)

  • Instance level (traditional): POSOperations(project).GetAll()

Both patterns work identically and are equally valid. The descriptor automatically handles instantiation when called at class level.

Usage:

class POSOperations(BaseOperations):
    @wrap_enumerable
    @OperationsMethod
    def GetAll(self):
        # Implementation
        return self.project.GetAllPOS()

# Both work:
pos_list = POSOperations.GetAll(project)  # Class-level
pos_list = POSOperations(project).GetAll()  # Instance-level
class flexicon.code.BaseOperations.BaseOperations(project)[source]

Bases: object

Base class for all FLEx operation classes.

Provides common reordering functionality that works with any FLEx Owning Sequence (OS) collection. Subclasses must override _GetSequence() to specify which OS property to reorder.

All 43 operation classes inherit from this base class, gaining access to 7 reordering methods without code duplication.

Reordering Safety:
  • Reordering is SAFE - preserves all data connections

  • GUIDs, references, properties, and children remain intact

  • Only changes the sequence position (index)

  • Uses safe Clear/Add pattern for all operations

Linguistic Significance:
  • Reordering changes linguistic meaning and behavior

  • Senses: First sense is primary

  • Allomorphs: First matching allomorph selected by parser

  • Examples: Order may reflect preference or pedagogy

  • Reorder only when linguistically justified

Usage:

from flexlibs2 import FLExProject

project = FLExProject()
project.OpenProject("MyProject", writeEnabled=True)

entry = list(project.LexiconAllEntries())[0]

# All operation classes have these methods:

# Sort senses alphabetically
project.Senses.Sort(entry,
                   key_func=lambda s: project.Senses.GetGloss(s))

# Move sense up one position
sense = entry.SensesOS[2]
project.Senses.MoveUp(entry, sense)

# Move allomorph to specific index
allo = entry.AlternateFormsOS[3]
project.Allomorphs.MoveToIndex(entry, allo, 0)

# Swap two examples
ex1 = sense.ExamplesOS[0]
ex2 = sense.ExamplesOS[1]
project.Examples.Swap(ex1, ex2)

project.CloseProject()
Sort(*args, **kwargs)[source]

Automatically instantiate and call the method.

MoveUp(*args, **kwargs)[source]

Automatically instantiate and call the method.

MoveDown(*args, **kwargs)[source]

Automatically instantiate and call the method.

MoveToIndex(*args, **kwargs)[source]

Automatically instantiate and call the method.

MoveBefore(*args, **kwargs)[source]

Automatically instantiate and call the method.

MoveAfter(*args, **kwargs)[source]

Automatically instantiate and call the method.

Swap(*args, **kwargs)[source]

Automatically instantiate and call the method.

GetSyncableProperties(*args, **kwargs)[source]

Automatically instantiate and call the method.

ApplySyncableProperties(*args, **kwargs)[source]

Automatically instantiate and call the method.

CompareTo(*args, **kwargs)[source]

Automatically instantiate and call the method.

flexicon.code.FLExGlobals module

flexicon.code.FLExGlobals.GetFWRegKey()[source]
flexicon.code.FLExGlobals.InitialiseFWGlobals()[source]

flexicon.code.FLExInit module

flexicon.code.FLExInit.FLExInitialize()[source]

Initialize the Fieldworks libraries. An application should call this as the first thing it does.

flexicon.code.FLExInit.FLExCleanup()[source]

Close up the Fieldworks libraries. An application should call this before exiting.

flexicon.code.FLExLCM module

flexicon.code.FLExLCM.GetListOfProjects()[source]
flexicon.code.FLExLCM.OpenProject(projectName)[source]

Open a FieldWorks project.

projectName:
  • Either the full path including “.fwdata” suffix, or

  • The name only, opened from the default project location.

flexicon.code.FLExProject module

flexicon.code.FLExProject.AllProjectNames()[source]

Returns a list of FieldWorks projects that are in the default location.

flexicon.code.FLExProject.OpenProjectInFW(projectName)[source]
class flexicon.code.FLExProject.FLExProject[source]

Bases: object

This class provides convenience methods for accessing a FieldWorks project by hiding some of the complexity of LCM. For functionality that isn’t provided here, LCM data and methods can be used directly via FLExProject.project, FLExProject.lp and FLExProject.lexDB. However, for long term use, new methods should be added to this class.

Usage:

from SIL.LCModel.Core.KernelInterfaces import ITsString, ITsStrBldr
from SIL.LCModel.Core.Text import TsStringUtils

project = FLExProject()
try:
    project.OpenProject("my project",
                        writeEnabled = True/False)
except (FP_ProjectError, FP_FileNotFoundError, FP_FileLockedError,
        System.IO.FileNotFoundException, System.IO.IOException,
        LcmFileLockedException, LcmDataMigrationForbiddenException) as e:
    #"Failed to open project"
    print(f"Error opening project: {e}")
    del project
    exit(1)

WSHandle = project.WSHandle('en')

# Traverse the whole lexicon
for lexEntry in project.LexiconAllEntries():
    headword = project.LexiconGetHeadword(lexEntry)

    # Use get_String() and set_String() with text fields:
    lexForm = lexEntry.LexemeFormOA
    lexEntryValue = ITsString(lexForm.Form.get_String(WSHandle)).Text
    newValue = convert_headword(lexEntryValue)
    mkstr = TsStringUtils.MakeString(newValue, WSHandle)
    lexForm.Form.set_String(WSHandle, mkstr)
OpenProject(projectName, writeEnabled=False, undoable=False)[source]

Open a project. The project must be closed with CloseProject() to save any changes, and release the lock.

projectName:
  • Either the full path including “.fwdata” suffix, or

  • The name only, to open from the default project location.

writeEnabled:

Enables changes to be written to the project, which will be saved on a call to CloseProject(). LCM will raise an exception if changes are attempted without opening the project in this mode.

undoable:

Enable full undo stack integration with FLEx Ctrl+Z. When True, operations wrapped in UndoableOperation() will appear in FLEx’s Undo menu. When False (default), uses rollback-only transactions via Transaction().

Only valid when writeEnabled=True. Ignored if False.

Phase 2 feature: requires LCM BeginUndoTask/EndUndoTask support. See docs/internal/RESEARCH_NEEDED.md for details.

Note

A call to OpenProject() may fail with a FP_FileLockedError exception if the project is open in Fieldworks (or another application). To avoid this, project sharing can be enabled within the Fieldworks Project Properties dialog. In the Sharing tab, turn on the option “Share project contents with programs on this computer”.

CloseProject()[source]

Save any pending changes and dispose of the LCM object.

property Cache

The underlying LcmCache. For advanced users dropping to raw LCM.

Provides discoverable access to the LcmCache instance that backs this project. Most users should prefer the operation classes (e.g. project.Phonemes, project.LexEntry), but this escape hatch is available for cases where raw LCM access is required.

Returns:

The underlying SIL.LCModel cache instance.

Return type:

LcmCache

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject")
>>> cache = project.Cache
>>> # Use cache.ServiceLocator, cache.MainCacheAccessor, etc.
GetService(interface_type)[source]

Get an LCM service or factory by interface type.

Discoverable wrapper around self.project.ServiceLocator.GetService(interface_type). Use this to obtain factories and services when no higher-level operation class exposes the functionality you need.

Parameters:

interface_type – The .NET interface type to resolve (e.g. IPhPhonemeFactory).

Returns:

The service or factory instance registered for interface_type.

Example

>>> from SIL.LCModel import IPhPhonemeFactory
>>> factory = project.GetService(IPhPhonemeFactory)
>>> phoneme = factory.Create()
GetFactory(interface_type)[source]

Resolve an LCM factory or service by interface type.

Discoverable entry point for factory lookup that works around a pythonnet limitation: the generic ILcmServiceLocator.GetInstance<T>() method is not reachable via pythonnet’s subscript syntax (GetInstance[T]()), which raises AttributeError on some pythonnet builds.

Two resolution paths are tried in order:

  1. Direct overload-resolved call: ServiceLocator.GetInstance(interface_type). Pythonnet normally binds this to the non-generic GetInstance(Type) overload. This is the pattern used throughout flexlibs2.

  2. Reflection: locate the parameterless GetInstance<T>() generic method, bind T to interface_type, and invoke. The resolved MethodInfo is cached on the FLExProject instance to avoid rescanning reflection on every call.

Prefer this method when you need a factory and either:
  • GetService returned None for a registered interface, or

  • you want the explicit “this is a factory” semantic.

Parameters:

interface_type – A pythonnet interface type (e.g. IMoInflAffMsaFactory).

Returns:

The factory or service instance registered for interface_type.

Raises:

Example

>>> from SIL.LCModel import IMoInflAffMsaFactory
>>> factory = project.GetFactory(IMoInflAffMsaFactory)
>>> msa = factory.Create()
Transaction(label='transaction')[source]

Return a context manager for a safe rollback transaction.

If an exception occurs inside the with block, all LCM changes made within that block are rolled back to the state at the start of the block. If no exception occurs, changes are committed (saved at CloseProject).

This is Phase 1 (rollback-only) behavior. Transactions do NOT appear in the FLEx Ctrl+Z undo menu; they are programmatic safety nets only.

Parameters:

label (str) – Human-readable description for logging. Default: “transaction”

Returns:

Context manager

Return type:

_FLExTransaction

Raises:

FP_ReadOnlyError – If project is not open (raised at write time, not here)

Example:

project = FLExProject()
project.OpenProject("MyProject", writeEnabled=True)
try:
    with project.Transaction("import batch"):
        for word, gloss in data:
            entry = project.LexEntry.Create(word, "stem")
            project.Senses.Create(entry, gloss, "en")
except Exception as e:
    print(f"Import failed and was rolled back: {e}")
project.CloseProject()

Note

Nesting is supported and safe. Each with block calls Mark() independently, creating a separate mark token on the LCM undo stack. An inner rollback rolls back only to the inner mark; an outer rollback rolls back everything done inside it – including work done by inner blocks that already exited cleanly (there is no two-phase commit; “commit” is simply not rolling back). This is the desired semantics for batch operations: a caller’s outer with project.Transaction("batch"): captures every write made inside it, including the per-method _TransactionCM blocks that individual Operations methods use internally.

See also

UndoableOperation() - Phase 2 (pending research), adds to FLEx Ctrl+Z menu

SaveChanges()[source]

Save all pending changes to disk without closing the project.

This is equivalent to what CloseProject() does internally before Dispose(). Useful after a successful Transaction block to ensure changes are persisted.

Note

Only valid for write-enabled projects. Does NOT call EndNonUndoableTask() - the session stays open.

Raises:

FP_ReadOnlyError – If project is not write-enabled.

Example:

with project.Transaction("import batch"):
    for word in words:
        project.LexEntry.Create(word, "stem")
project.SaveChanges()  # Persist the batch before continuing
UndoableOperation(label)[source]

Return a context manager for an undoable operation.

Changes made within the block appear as a single named operation in FLEx’s Ctrl+Z undo menu. The project MUST be opened with undoable=True for this to work.

Parameters:

label (str) – Name shown in FLEx undo menu (e.g. “Add entry ‘run’”)

Returns:

Context manager

Return type:

_FLExUndoableOperation

Raises:

Example:

project = FLExProject()
project.OpenProject("MyProject", writeEnabled=True, undoable=True)

with project.UndoableOperation("Add entry 'run'"):
    entry = project.LexEntry.Create("run", "stem")
    project.Senses.Create(entry, "to move quickly", "en")

# Now "Add entry 'run'" appears in FLEx Edit > Undo
project.Undo()   # Ctrl+Z equivalent
project.Redo()   # Ctrl+Y equivalent

Note

Phase 2 feature. Requires research-verified LCM APIs. See docs/internal/RESEARCH_NEEDED.md and docs/TRANSACTION_GUIDE.md.

Atomicity caveat (Phase 2): BeginUndoTask/EndUndoTask is NOT transactional. If an exception is raised inside the block, partial mutations already committed to the LCM cache are NOT automatically rolled back. The FLEx Ctrl+Z undo entry may be absent or incomplete. Rollback/atomicity applies only to the Phase-1 Transaction() (mark + RollbackToMark) path. Callers that require atomic all-or-nothing semantics should use Transaction() instead.

Undo()[source]

Undo the last UndoableOperation.

Reverses the changes of the last operation added with UndoableOperation(). Only valid when the project was opened with undoable=True.

Returns:

True if undo succeeded, False if nothing to undo.

Return type:

bool

Raises:

FP_TransactionError – If project not opened with undoable=True

Example:

with project.UndoableOperation("Add entry"):
    project.LexEntry.Create("word", "stem")

project.Undo()  # Removes the entry
Redo()[source]

Redo the last undone UndoableOperation.

Re-applies a change reversed by Undo(). Only valid when the project was opened with undoable=True.

Returns:

True if redo succeeded, False if nothing to redo.

Return type:

bool

Raises:

FP_TransactionError – If project not opened with undoable=True

Example:

with project.UndoableOperation("Add entry"):
    project.LexEntry.Create("word", "stem")

project.Undo()   # Removes the entry
project.Redo()   # Restores the entry
property POS

Access to Parts of Speech operations.

Returns:

Instance providing POS management methods

Return type:

POSOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all parts of speech
>>> for pos in project.POS.GetAll():
...     print(f"{project.POS.GetName(pos)} ({project.POS.GetAbbreviation(pos)})")
>>> # Create a new POS
>>> noun = project.POS.Create("Noun", "N")
>>> # Find and update
>>> verb = project.POS.Find("Verb")
>>> if verb:
...     project.POS.SetAbbreviation(verb, "V")
property LexEntry

Access to Lexical Entry operations.

Returns:

Instance providing lexical entry management methods

Return type:

LexEntryOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all entries
>>> for entry in project.LexEntry.GetAll():
...     print(project.LexEntry.GetHeadword(entry))
>>> # Create a new entry
>>> entry = project.LexEntry.Create("run", "stem")
>>> # Add a sense
>>> sense = project.LexEntry.AddSense(entry, "to move rapidly on foot")
>>> # Set citation form
>>> project.LexEntry.SetCitationForm(entry, "run")
property Texts

Access to Text operations.

Returns:

Instance providing text management methods

Return type:

TextOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a new text
>>> text = project.Texts.Create("Genesis")
>>> # List all texts
>>> for t in project.Texts.GetAll():
...     print(project.Texts.GetName(t))
>>> # Update text name
>>> project.Texts.SetName(text, "Genesis Chapter 1")
property Wordforms

727+ commits in 2024).

Returns:

Instance providing wordform inventory management methods

Return type:

WfiWordformOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Find or create wordform (most common pattern)
>>> wf = project.Wordforms.FindOrCreate("hlauka")
>>> # Get all analyses
>>> for analysis in project.Wordforms.GetAnalyses(wf):
...     approved = project.WfiAnalyses.IsHumanApproved(analysis)
...     print(f"Analysis: {'approved' if approved else 'parser guess'}")
>>> # Set approved analysis
>>> if wf.AnalysesOC.Count > 0:
...     project.Wordforms.SetApprovedAnalysis(wf, wf.AnalysesOC[0])
Type:

Access to wordform operations (Work Stream 3 - MOST ACTIVE

property WfiAnalyses

Access to wordform analysis operations (Work Stream 3).

Returns:

Instance providing wordform analysis management methods

Return type:

WfiAnalysisOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get wordform and create analysis
>>> wf = project.Wordforms.FindOrCreate("hlauka")
>>> analysis = project.WfiAnalyses.Create(wf)
>>> # Set category (part of speech)
>>> verb = project.POS.Find("verb")
>>> if verb:
...     project.WfiAnalyses.SetCategory(analysis, verb)
>>> # Mark as human-approved
>>> project.WfiAnalyses.Approve(analysis)
>>> # Get morph bundles
>>> bundles = project.WfiAnalyses.GetMorphBundles(analysis)
property Paragraphs

Access to paragraph operations.

Returns:

Instance providing paragraph management methods

Return type:

ParagraphOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> text = list(project.Texts.GetAll())[0]
>>> para = list(text.ContentsOA.ParagraphsOS)[0]
>>> # Get translations
>>> trans = project.Paragraphs.GetTranslations(para)
>>> # Set translation
>>> project.Paragraphs.SetTranslation(para, "In the beginning...", "en")
>>> # Add note
>>> note = project.Paragraphs.AddNote(para, "Check translation")
>>> # Get style
>>> style = project.Paragraphs.GetStyleName(para)
property Segments

Access to segment operations.

Returns:

Instance providing segment management methods

Return type:

SegmentOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all segments in a paragraph
>>> para = project.Object(para_hvo)
>>> for segment in project.Segments.GetAll(para):
...     baseline = project.Segments.GetBaselineText(segment)
...     print(baseline)
>>> # Set translations
>>> segment = list(project.Segments.GetAll(para))[0]
>>> project.Segments.SetFreeTranslation(segment, "In the beginning...")
>>> project.Segments.SetLiteralTranslation(segment, "In-the beginning...")
property Phonemes

Access to phoneme operations.

Returns:

Instance providing phoneme management methods

Return type:

PhonemeOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all phonemes
>>> for phoneme in project.Phonemes.GetAll():
...     repr = project.Phonemes.GetRepresentation(phoneme)
...     desc = project.Phonemes.GetDescription(phoneme)
...     print(f"{repr}: {desc}")
>>> # Create a new phoneme
>>> phoneme = project.Phonemes.Create("/p/")
>>> project.Phonemes.SetDescription(phoneme, "voiceless bilabial stop")
>>> # Add allophonic codes
>>> project.Phonemes.AddCode(phoneme, "[p]")
>>> project.Phonemes.AddCode(phoneme, "[pʰ]")
>>> # Check phoneme type
>>> if project.Phonemes.IsConsonant(phoneme):
...     print("Consonant phoneme")
property NaturalClasses

Access to natural class operations.

Returns:

Instance providing natural class management methods

Return type:

NaturalClassOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all natural classes
>>> for nc in project.NaturalClasses.GetAll():
...     name = project.NaturalClasses.GetName(nc)
...     print(f"Natural class: {name}")
>>> # Create a new natural class
>>> nc = project.NaturalClasses.Create("Voiced Stops")
>>> # Add phonemes to the class
>>> phoneme_b = project.Phonemes.Find("/b/")
>>> project.NaturalClasses.AddPhoneme(nc, phoneme_b)
property Environments

Access to phonological environment operations.

Returns:

Instance providing environment management methods

Return type:

EnvironmentOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all environments
>>> for env in project.Environments.GetAll():
...     name = project.Environments.GetName(env)
...     repr = project.Environments.GetStringRepresentation(env)
...     print(f"{name}: {repr}")
>>> # Create a new environment
>>> env = project.Environments.Create("Between vowels", "V_V")
property Allomorphs

Access to allomorph operations.

Returns:

Instance providing allomorph management methods

Return type:

AllomorphOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all allomorphs for an entry
>>> entry = project.LexiconGetFirstEntry()
>>> for allo in project.Allomorphs.GetAll(entry):
...     form = project.Allomorphs.GetForm(allo)
...     print(f"Allomorph: {form}")
>>> # Create a new allomorph
>>> allo = project.Allomorphs.Create(entry, "-ed")
property MorphRules

Access to morphological rule operations.

Returns:

Instance providing morph rule management methods

Return type:

MorphRuleOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all compound rules
>>> for rule in project.MorphRules.GetAllCompoundRules():
...     name = project.MorphRules.GetName(rule)
...     print(f"{name} ({rule.ClassName})")
>>> # Create a compound rule
>>> rule = project.MorphRules.CreateCompoundRule("Noun-Noun Compound")
property InflectionFeatures

Access to inflection feature operations.

Returns:

Instance providing inflection feature management methods

Return type:

InflectionFeatureOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all inflection classes
>>> for ic in project.InflectionFeatures.GetAllClasses():
...     name = project.InflectionFeatures.GetClassName(ic)
...     print(f"Inflection class: {name}")
>>> # Get all features
>>> for feat in project.InflectionFeatures.GetAllFeatures():
...     name = project.InflectionFeatures.GetFeatureName(feat)
...     print(f"Feature: {name}")
property Features

Discoverability alias for InflectionFeatures.

Inflection features (closed features with symbolic values like +/- gender, person 1/2/3, etc.) are owned by LangProject.MsFeatureSystemOA. The full CRUD surface – Create, CreateValue, Find, Exists, MakeFeatStruc, CreateClosedFeatureWithValues, plus catalog import from MGA EticGlossList – lives on project.InflectionFeatures. This alias exists so callers thinking in FLEx UI terminology (the “Features” tab) can find the wrapper from either spelling.

For phonological features (PhFeatureSystemOA, owned by phonemes and natural classes) see project.PhonFeatures.

Example

>>> # Equivalent calls:
>>> project.Features.Create("gender", "gen")
>>> project.InflectionFeatures.Create("gender", "gen")
>>>
>>> # One-shot for the very common case:
>>> feature, values = project.Features.CreateClosedFeatureWithValues(
...     name="gender", abbreviation="gen",
...     values=[("masculine", "m"), ("feminine", "f"), ("neuter", "n")],
... )
property GramCat

Access to grammatical category operations.

Returns:

Instance providing grammatical category management methods

Return type:

GramCatOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all grammatical categories
>>> for gc in project.GramCat.GetAll():
...     name = project.GramCat.GetName(gc)
...     print(f"Category: {name}")
>>> # Create a new category
>>> gc = project.GramCat.Create("Transitive")
property PhonRules

Access to phonological rule operations.

Returns:

Instance providing phonological rule management methods

Return type:

PhonologicalRuleOperations

Example

>>> from flexlibs2 import FLExProject, Seg, NC
>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a phonological rule
>>> rule = project.PhonRules.Create("Voicing Assimilation",
...     "Voiceless stops become voiced between vowels")
>>> # Wire input, output, and contexts via WireRule (the composer)
>>> phoneme_t = project.Phonemes.Find("/t/")
>>> phoneme_d = project.Phonemes.Find("/d/")
>>> vowels = project.NaturalClasses.Find("Vowels")
>>> project.PhonRules.WireRule(rule,
...     input_pattern=[Seg(phoneme_t)],
...     output_change=[Seg(phoneme_d)],
...     left_context=[NC(vowels)],
...     right_context=[NC(vowels)],
... )
property PhonFeatures

Access to phonological feature operations.

Returns:

Instance providing phonological feature and feature-value management methods, including catalog import from the MGA PhonFeatsEticGlossList.

Return type:

PhonFeatureOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Bulk-import the standard MGA feature set
>>> result = project.PhonFeatures.ImportCatalog()
>>> print(f"Created {result.created_count} entries")
>>> # Create a specific feature
>>> cons = project.PhonFeatures.CreateFromCatalog("fPAConsonantal")
>>> # Inspect its +/- values
>>> for v in project.PhonFeatures.GetValues(cons):
...     print(project.PhonFeatures.GetAbbreviation(v))
property Strata

Access to stratum operations.

Strata are the ordered morphology/phonology layers owned by LangProject.MorphologicalDataOA.StrataOS and referenced by IMoInflAffixTemplate.StratumRA, IMoDerivAffMsa.StratumRA, IMoStemMsa.StratumRA, IMoCompoundRule.StratumRA, and IPhPhonologicalRule.StratumRA.

Returns:

Instance providing stratum management methods.

Return type:

StratumOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Enumerate strata
>>> for stratum in project.Strata.GetAll():
...     print(project.Strata.GetName(stratum))
>>> # Create a new stratum
>>> new_stratum = project.Strata.Create("Stem", abbreviation="stem")
>>> # Round-trip syncable properties
>>> props = project.Strata.GetSyncableProperties(new_stratum)
property Senses

Access to lexical sense operations.

Returns:

Instance providing sense management methods

Return type:

LexSenseOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all senses for an entry
>>> entry = list(project.LexiconAllEntries())[0]
>>> for sense in project.Senses.GetAll(entry):
...     gloss = project.Senses.GetGloss(sense)
...     print(f"Sense: {gloss}")
>>> # Create a new sense
>>> sense = project.Senses.Create(entry, "to run", "en")
>>> # Set definition
>>> project.Senses.SetDefinition(sense, "To move swiftly on foot")
>>> # Add semantic domain
>>> domains = project.GetAllSemanticDomains()  # default: recursive=True
>>> if domains:
...     project.Senses.AddSemanticDomain(sense, domains[0])
property MSA

Access to morphosyntactic-analysis (MSA) creation operations.

Pairs with the reading wrapper in flexlibs2.code.Lexicon.morphosyntax_analysis and the iteration helper in msa_collection. Handles the four concrete MSA types (stem, derivational affix, inflectional affix, unclassified affix) and auto-attaches the new MSA to the supplied sense via sense.MorphoSyntaxAnalysisRA.

Returns:

Instance providing MSA creation methods.

Return type:

MSAOperations

Example

>>> entry = list(project.LexiconAllEntries())[0]
>>> sense = entry.SensesOS[0]
>>> verb_pos = project.GramCat.Find("Verb")
>>> # Stem MSA with POS = Verb
>>> project.MSA.CreateStem(sense, verb_pos)
>>> # Derivational affix that turns nouns into verbs
>>> n_pos = project.GramCat.Find("Noun")
>>> v_pos = project.GramCat.Find("Verb")
>>> project.MSA.CreateDerivAff(sense, from_pos=n_pos, to_pos=v_pos)
property Examples

Access to example sentence operations.

Returns:

Instance providing example sentence management methods

Return type:

ExampleOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get first entry and sense
>>> entry = project.LexiconAllEntries().__next__()
>>> sense = entry.SensesOS[0]
>>> # Get all examples
>>> for example in project.Examples.GetAll(sense):
...     text = project.Examples.GetExample(example)
...     trans = project.Examples.GetTranslation(example)
...     print(f"{text} - {trans}")
>>> # Create a new example
>>> example = project.Examples.Create(sense, "The cat slept.")
>>> project.Examples.SetTranslation(example, "Le chat a dormi.")
>>> project.Examples.SetReference(example, "Corpus A:123")
property LexReferences

Access to lexical reference and relation operations.

Returns:

Instance providing lexical reference management methods

Return type:

LexReferenceOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all reference types
>>> for ref_type in project.LexReferences.GetAllTypes():
...     name = project.LexReferences.GetTypeName(ref_type)
...     mapping = project.LexReferences.GetMappingType(ref_type)
...     print(f"{name}: {mapping}")
>>> # Create a synonym relation
>>> syn_type = project.LexReferences.FindType("Synonym")
>>> if not syn_type:
...     syn_type = project.LexReferences.CreateType("Synonym", "Symmetric")
>>> # Link two senses
>>> entry1 = project.LexEntry.Find("run")
>>> entry2 = project.LexEntry.Find("jog")
>>> if entry1 and entry2:
...     sense1 = list(project.Senses.GetAll(entry1))[0]
...     sense2 = list(project.Senses.GetAll(entry2))[0]
...     ref = project.LexReferences.Create(syn_type, [sense1, sense2])
>>> # Get all references for a sense
>>> for ref in project.LexReferences.GetAll(sense1):
...     targets = project.LexReferences.GetTargets(ref)
...     print(f"Related to {len(targets)} items")
property ReversalIndexes

Access to reversal index operations (Work Stream 3).

Returns:

Instance providing reversal index management methods

Return type:

ReversalIndexOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create English reversal index
>>> en_ws = project.WSHandle('en')
>>> idx = project.ReversalIndexes.Create("English", en_ws)
>>> # Find by writing system
>>> idx = project.ReversalIndexes.FindByWritingSystem(en_ws)
>>> # Get all entries in index
>>> for entry in project.ReversalIndexes.GetEntries(idx):
...     form = project.ReversalEntries.GetForm(entry)
...     print(f"Reversal: {form}")
property ReversalEntries

Access to reversal index entry operations (Work Stream 3).

Returns:

Instance providing reversal entry management methods

Return type:

ReversalIndexEntryOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get reversal index
>>> idx = project.ReversalIndexes.FindByWritingSystem('en')
>>> # Create reversal entry
>>> entry = project.ReversalEntries.Create(idx, "run")
>>> # Link to lexical sense
>>> lex_entry = project.LexEntry.Find("hlauka")
>>> if lex_entry and lex_entry.SensesOS.Count > 0:
...     sense = lex_entry.SensesOS[0]
...     project.ReversalEntries.AddSense(entry, sense)
property SemanticDomains

Access to semantic domain operations.

Returns:

Instance providing semantic domain management methods

Return type:

SemanticDomainOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all semantic domains
>>> for domain in project.SemanticDomains.GetAll():
...     number = project.SemanticDomains.GetNumber(domain)
...     name = project.SemanticDomains.GetName(domain)
...     print(f"{number} - {name}")
>>> # Find a specific domain
>>> walk_domain = project.SemanticDomains.Find("7.2.1")
>>> if walk_domain:
...     desc = project.SemanticDomains.GetDescription(walk_domain)
...     senses = project.SemanticDomains.GetSensesInDomain(walk_domain)
...     print(f"Domain has {len(senses)} senses")
>>> # Create a custom domain
>>> custom = project.SemanticDomains.Create("Technology", "900")
property Pronunciations

Access to pronunciation operations.

Returns:

Instance providing pronunciation management methods

Return type:

PronunciationOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all pronunciations for an entry
>>> entry = list(project.LexiconAllEntries())[0]
>>> for pron in project.Pronunciations.GetAll(entry):
...     ipa = project.Pronunciations.GetForm(pron, "en-fonipa")
...     print(f"IPA: {ipa}")
>>> # Create a new pronunciation
>>> pron = project.Pronunciations.Create(entry, "rʌn", "en-fonipa")
>>> # Add audio file
>>> project.Pronunciations.AddMediaFile(pron, "/path/to/audio.wav")
>>> # Get media files
>>> media = project.Pronunciations.GetMediaFiles(pron)
>>> print(f"Audio files: {len(media)}")
property Variants

Access to variant form operations.

Returns:

Instance providing variant management methods

Return type:

VariantOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all variant types
>>> for vtype in project.Variants.GetAllTypes():
...     name = project.Variants.GetTypeName(vtype)
...     print(f"Variant type: {name}")
>>> # Find a specific variant type
>>> spelling_type = project.Variants.FindType("Spelling Variant")
>>> # Create a variant
>>> entry = project.LexEntry.Find("color")
>>> variant = project.Variants.Create(entry, "colour", spelling_type)
>>> # Get all variants for an entry
>>> for var in project.Variants.GetAll(entry):
...     form = project.Variants.GetForm(var)
...     vtype = project.Variants.GetType(var)
...     print(f"Variant: {form}")
>>> # For irregularly inflected forms
>>> go_entry = project.LexEntry.Find("go")
>>> went_entry = project.LexEntry.Find("went")
>>> irregular_type = project.Variants.FindType("Irregularly Inflected Form")
>>> variant_ref = project.Variants.Create(went_entry, "went", irregular_type)
>>> project.Variants.AddComponentLexeme(variant_ref, go_entry)
property Etymology

Access to etymology operations.

Returns:

Instance providing etymology tracking methods

Return type:

EtymologyOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get an entry
>>> entry = project.LexEntry.Find("telephone")
>>> # Create etymology for compound word components
>>> etym1 = project.Etymology.Create(entry, "Ancient Greek", "τηλε (tele)", "far, distant")
>>> project.Etymology.SetComment(etym1, "Combining form from Greek τῆλε")
>>> etym2 = project.Etymology.Create(entry, "Ancient Greek", "φωνή (phōnē)", "sound, voice")
>>> # Query etymologies
>>> for etym in project.Etymology.GetAll(entry):
...     source = project.Etymology.GetSource(etym)
...     form = project.Etymology.GetForm(etym)
...     gloss = project.Etymology.GetGloss(etym)
...     print(f"{source}: {form} ({gloss})")
property PossibilityLists

Access to generic possibility list operations.

Returns:

Instance providing possibility list management methods

Return type:

PossibilityListOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all possibility lists in the project
>>> for poss_list in project.PossibilityLists.GetAllLists():
...     name = project.PossibilityLists.GetListName(poss_list)
...     items = project.PossibilityLists.GetItems(poss_list)
...     print(f"{name}: {len(items)} items")
Semantic Domains: 1435 items
Parts of Speech: 45 items
Text Genres: 12 items
...
>>> # Work with a specific list
>>> genre_list = project.PossibilityLists.FindList("Text Genres")
>>> if genre_list:
...     # Get all items
...     for item in project.PossibilityLists.GetItems(genre_list):
...         name = project.PossibilityLists.GetItemName(item)
...         depth = project.PossibilityLists.GetDepth(item)
...         print(f"{'  ' * depth}{name}")
...     # Create a new genre
...     narrative = project.PossibilityLists.CreateItem(
...         genre_list, "Narrative", "en")
...     # Create a sub-genre
...     folktale = project.PossibilityLists.CreateItem(
...         genre_list, "Folktale", "en", parent=narrative)
...     # Move items in hierarchy
...     project.PossibilityLists.MoveItem(folktale, None)  # Move to top
property LocalizedLists

Access to localized possibility-list translation-pack imports.

Localized lists merge translated Name/Abbreviation alternatives onto canonical possibility-list items (SemanticDomains, AnthroList, DomainTypes, …) by GUID. Translation packs ship at <FWCodeDir>/Templates/LocalizedLists-<lang>.zip.

Order matters: call after the relevant *Operations .ImportCatalog (e.g. project.SemanticDomains.ImportCatalog) has seeded canonical items. Without canonical items present, the merger has nothing to land on.

Returns:

Instance providing single-WS Import(code) and project-wide ImportForAllAnalysisWritingSystems().

Return type:

LocalizedListsOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> project.SemanticDomains.ImportCatalog()
>>> # Single WS:
>>> project.LocalizedLists.Import("fr")
>>> # Or fan out across every enabled analysis WS:
>>> result = project.LocalizedLists.ImportForAllAnalysisWritingSystems()
>>> print(result.imported)
>>> for code, reason in result.skipped:
...     print(f"  skipped {code}: {reason}")
property CustomFields

Access to custom field operations.

Returns:

Instance providing custom field management methods

Return type:

CustomFieldOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all custom fields for entries
>>> entry_fields = project.CustomFields.GetAllFields("LexEntry")
>>> for field_id, label in entry_fields:
...     print(f"Field: {label} (ID: {field_id})")
>>> # Find a specific field
>>> field_id = project.CustomFields.FindField("LexEntry", "Etymology Source")
>>> # Get and set field values
>>> entry = project.LexEntry.Find("run")
>>> if field_id:
...     value = project.CustomFields.GetValue(entry, "Etymology Source")
...     print(f"Current value: {value}")
...     project.CustomFields.SetValue(entry, "Etymology Source", "Latin currere")
>>> # Work with list fields
>>> sense = entry.SensesOS[0]
>>> regions = project.CustomFields.GetListValues(sense, "Regions")
>>> project.CustomFields.AddListValue(sense, "Regions", "North")
property WritingSystems

Access to writing system operations.

Returns:

Instance providing writing system management methods

Return type:

WritingSystemOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all writing systems
>>> for ws in project.WritingSystems.GetAll():
...     name = project.WritingSystems.GetDisplayName(ws)
...     tag = project.WritingSystems.GetLanguageTag(ws)
...     print(f"{name} ({tag})")
>>> # Configure a writing system
>>> ws = list(project.WritingSystems.GetVernacular())[0]
>>> project.WritingSystems.SetFontName(ws, "Charis SIL")
>>> project.WritingSystems.SetFontSize(ws, 14)
>>> # Set RTL for Arabic
>>> if project.WritingSystems.Exists("ar"):
...     project.WritingSystems.SetRightToLeft("ar", True)
property WfiGlosses

Access to wordform gloss operations (Work Stream 3).

Returns:

Instance providing wordform gloss management methods

Return type:

WfiGlossOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get analysis and create gloss
>>> analysis = project.WfiAnalyses.Create(wordform)
>>> gloss = project.WfiGlosses.Create(analysis, "run", project.WSHandle('en'))
>>> # Mark as human-approved
>>> project.WfiGlosses.Approve(gloss)
>>> # Get all glosses
>>> for g in project.WfiGlosses.GetAll(analysis):
...         form = project.WfiGlosses.GetForm(g, "en")
...         print(f"Gloss: {form}")
property WfiMorphBundles

Access to wordform morpheme bundle operations (Work Stream 3).

Returns:

Instance providing morpheme bundle management methods

Return type:

WfiMorphBundleOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create morpheme bundles for morphological breakdown
>>> analysis = project.WfiAnalyses.Create(wordform)
>>> stem = project.WfiMorphBundles.Create(analysis, "hlauk-")
>>> suffix = project.WfiMorphBundles.Create(analysis, "-a")
>>> # Link to lexical entries
>>> stem_entry = project.LexEntry.Find("hlauk")
>>> if stem_entry and stem_entry.SensesOS.Count > 0:
...     project.WfiMorphBundles.SetSense(stem, stem_entry.SensesOS[0])
>>> # Set morpheme type
>>> project.WfiMorphBundles.SetMorphemeType(stem, "stem")
property Media

Access to media file operations.

Returns:

Instance providing media file management methods

Return type:

MediaOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all media files
>>> for media in project.Media.GetAll():
...     filename = project.Media.GetFilename(media)
...     mtype = project.Media.GetMediaType(media)
...     print(f"{filename} ({mtype})")
>>> # Add a media file
>>> media = project.Media.Create("/path/to/audio.wav", "My Recording")
>>> # Copy file to project
>>> project.Media.CopyToProject(media)
>>> # Find orphaned media
>>> orphans = project.Media.GetOrphanedMedia()
>>> print(f"Found {len(orphans)} orphaned files")
property Notes

Access to note and annotation operations.

Returns:

Instance providing note management methods

Return type:

NoteOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a note on an entry
>>> entry = project.LexEntry.Find("run")
>>> note = project.Notes.Create(entry, "Check etymology", "en")
>>> # Add a reply
>>> reply = project.Notes.AddReply(note, "Verified - from Latin currere", "en")
>>> # Get all notes for an object
>>> for n in project.Notes.GetAll(entry):
...     content = project.Notes.GetContent(n, "en")
...     replies = project.Notes.GetReplies(n)
...     print(f"Note: {content} ({len(replies)} replies)")
property Filters

Access to filter and query operations.

Returns:

Instance providing filter management methods

Return type:

FilterOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a filter for incomplete entries
>>> filter_def = {
...     "name": "Incomplete Entries",
...     "type": "LexEntry",
...     "conditions": [
...         {"field": "SensesOS", "operator": "isEmpty"}
...     ]
... }
>>> filter_obj = project.Filters.Create(filter_def)
>>> # Apply the filter
>>> results = project.Filters.ApplyFilter(filter_obj)
>>> print(f"Found {len(results)} incomplete entries")
>>> # Export filter
>>> json_str = project.Filters.ExportFilter(filter_obj)
property Discourse

Access to discourse chart operations.

Returns:

Instance providing discourse chart management methods

Return type:

DiscourseOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get a text
>>> text = list(project.TextCatalog())[0]
>>> # Create a discourse chart
>>> chart = project.Discourse.CreateChart(text, "Constituent Chart", "en")
>>> # Add rows
>>> row1 = project.Discourse.AddRow(chart, 0)
>>> # Get all charts
>>> for c in project.Discourse.GetAllCharts():
...     name = project.Discourse.GetChartName(c, "en")
...     rows = project.Discourse.GetRows(c)
...     print(f"Chart: {name} ({len(rows)} rows)")
property Person

Access to person operations for managing consultants, speakers, and researchers.

Returns:

Instance providing person management methods

Return type:

PersonOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a person
>>> consultant = project.Person.Create("Maria Garcia", "en")
>>> # Set properties
>>> project.Person.SetGender(consultant, "Female", "en")
>>> project.Person.SetEmail(consultant, "maria@example.com", "en")
>>> project.Person.SetEducation(consultant, "PhD Linguistics", "en")
>>> # Add residence
>>> location = project.Location.Find("Lima")
>>> if location:
...     project.Person.AddResidence(consultant, location)
>>> # Get all people
>>> for person in project.Person.GetAll():
...     name = project.Person.GetName(person)
...     email = project.Person.GetEmail(person)
...     print(f"{name}: {email}")
property Location

Access to location operations for managing geographic places.

Returns:

Instance providing location management methods

Return type:

LocationOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a location
>>> region = project.Location.Create("Cusco Region", "en", alias="CUS")
>>> project.Location.SetCoordinates(region, -13.5319, -71.9675)
>>> project.Location.SetElevation(region, 3400)
>>> # Create sublocation
>>> city = project.Location.CreateSublocation(region, "Cusco", "en")
>>> project.Location.SetDescription(city, "Historic capital of Inca Empire", "en")
>>> # Find nearby locations
>>> nearby = project.Location.GetNearby(city, radius_km=100)
>>> for loc in nearby:
...     name = project.Location.GetName(loc)
...     coords = project.Location.GetCoordinates(loc)
...     print(f"{name}: {coords}")
property Anthropology

Access to anthropology operations for managing cultural/ethnographic data.

Returns:

Instance providing anthropology management methods

Return type:

AnthropologyOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create anthropology items
>>> marriage = project.Anthropology.Create(
...     "Marriage Customs", "MAR", "586")
>>> project.Anthropology.SetDescription(marriage,
...     "Traditional marriage practices and ceremonies", "en")
>>> # Create subitem
>>> wedding = project.Anthropology.CreateSubitem(
...     marriage, "Wedding Ceremony", "WED", "586.1")
>>> # Link to text
>>> text = project.Texts.Find("Wedding Story")
>>> if text:
...     project.Anthropology.AddText(marriage, text)
>>> # Query items
>>> items = project.Anthropology.GetItemsForText(text)
>>> for item in items:
...     name = project.Anthropology.GetName(item)
...     code = project.Anthropology.GetAnthroCode(item)
...     print(f"{code}: {name}")
property ProjectSettings

Access to project settings operations.

Returns:

Instance providing project configuration methods

Return type:

ProjectSettingsOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get project info
>>> name = project.ProjectSettings.GetProjectName()
>>> desc = project.ProjectSettings.GetDescription("en")
>>> # Configure writing systems
>>> vern_wss = project.ProjectSettings.GetVernacularWSs()
>>> project.ProjectSettings.SetDefaultVernacular("qaa-x-spec")
>>> # Set default font
>>> project.ProjectSettings.SetDefaultFont("en", "Charis SIL")
>>> project.ProjectSettings.SetDefaultFontSize("en", 14)
property Publications

Access to publication operations.

Returns:

Instance providing publication management methods

Return type:

PublicationOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create publication
>>> pub = project.Publications.Create("Dictionary", "en")
>>> project.Publications.SetPageWidth(pub, 8.5)
>>> project.Publications.SetPageHeight(pub, 11)
>>> # Get all publications
>>> for p in project.Publications.GetAll():
...     name = project.Publications.GetName(p)
...     is_default = project.Publications.GetIsDefault(p)
...     print(f"{name} (default: {is_default})")
property Agents

Access to agent operations.

Returns:

Instance providing agent management methods

Return type:

AgentOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create human agent
>>> person = project.Person.Create("John Smith", "en")
>>> agent = project.Agents.CreateHumanAgent("John Smith", person)
>>> # Create parser agent
>>> parser = project.Agents.CreateParserAgent("MyParser", "1.0.0")
>>> # Query agents
>>> for a in project.Agents.GetAll():
...     name = project.Agents.GetName(a)
...     if project.Agents.IsHuman(a):
...         print(f"Human: {name}")
...     else:
...         version = project.Agents.GetVersion(a)
...         print(f"Parser: {name} v{version}")
property Confidence

Access to confidence level operations.

Returns:

Instance providing confidence management methods

Return type:

ConfidenceOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all confidence levels
>>> for level in project.Confidence.GetAll():
...     name = project.Confidence.GetName(level)
...     print(f"Confidence: {name}")
>>> # Create custom confidence level
>>> verified = project.Confidence.Create("Speaker Verified", "en")
>>> project.Confidence.SetDescription(verified,
...     "Confirmed by native speaker", "en")
property Overlays

Access to discourse overlay operations.

Returns:

Instance providing overlay management methods

Return type:

OverlayOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get a chart
>>> text = list(project.TextCatalog())[0]
>>> chart = project.Discourse.CreateChart(text, "Chart", "en")
>>> # Create overlay
>>> overlay = project.Overlays.Create(chart, "Temporal", "en")
>>> project.Overlays.SetVisible(overlay, True)
>>> # Get visible overlays
>>> for o in project.Overlays.GetVisibleOverlays(chart):
...     name = project.Overlays.GetName(o)
...     print(f"Overlay: {name}")
property TranslationTypes

Access to translation type operations.

Returns:

Instance providing translation type methods

Return type:

TranslationTypeOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get predefined types
>>> free = project.TranslationTypes.GetFreeTranslationType()
>>> literal = project.TranslationTypes.GetLiteralTranslationType()
>>> # Create custom type
>>> gloss = project.TranslationTypes.Create("Interlinear Gloss", "IG", "en")
>>> # Get all types
>>> for t in project.TranslationTypes.GetAll():
...     name = project.TranslationTypes.GetName(t)
...     abbr = project.TranslationTypes.GetAbbreviation(t)
...     print(f"{name} ({abbr})")
property AnnotationDefs

Access to annotation definition operations.

Returns:

Instance providing annotation definition methods

Return type:

AnnotationDefOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get all annotation definitions
>>> for defn in project.AnnotationDefs.GetAll():
...     name = project.AnnotationDefs.GetName(defn)
...     can_create = project.AnnotationDefs.GetUserCanCreate(defn)
...     print(f"{name} (user-creatable: {can_create})")
>>> # Create custom annotation type
>>> note_type = project.AnnotationDefs.Create("Field Note", "en")
>>> project.AnnotationDefs.SetUserCanCreate(note_type, True)
property Checks

Access to consistency check operations.

Returns:

Instance providing check management methods

Return type:

CheckOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create check type
>>> check = project.Checks.CreateCheckType("Missing Gloss", "en")
>>> project.Checks.SetDescription(check,
...     "Find senses without glosses", "en")
>>> # Run check
>>> results = project.Checks.RunCheck(check)
>>> print(f"Errors: {results['errors']}")
>>> print(f"Warnings: {results['warnings']}")
>>> # Get enabled checks
>>> for c in project.Checks.GetEnabledChecks():
...     name = project.Checks.GetName(c)
...     status = project.Checks.GetCheckStatus(c)
...     print(f"{name}: {status}")
property DataNotebook

Access to data notebook operations for research notes and observations.

Returns:

Instance providing notebook record management methods

Return type:

DataNotebookOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create notebook record
>>> record = project.DataNotebook.Create(
...     "Field Interview", "Notes from interview with speaker")
>>> project.DataNotebook.SetDateOfEvent(record, "2024-01-15")
>>> # Link researcher
>>> researcher = project.Person.Find("John Smith")
>>> project.DataNotebook.AddResearcher(record, researcher)
>>> # Create sub-record
>>> sub = project.DataNotebook.CreateSubRecord(
...     record, "Kinship Terms", "Analysis of family terms")
>>> # Set status
>>> project.DataNotebook.SetStatus(record, "Reviewed")
>>> # Query records
>>> for rec in project.DataNotebook.FindByResearcher(researcher):
...     title = project.DataNotebook.GetTitle(rec)
...     date = project.DataNotebook.GetDateOfEvent(rec)
...     print(f"{title} ({date})")
property ConstCharts

Access to constituent chart operations for discourse analysis.

Returns:

Instance providing constituent chart management methods

Return type:

ConstChartOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Create a constituent chart
>>> chart = project.ConstCharts.Create("Genesis 1 Analysis")
>>> # Set properties
>>> project.ConstCharts.SetName(chart, "Genesis 1 - Updated")
>>> # Get all charts
>>> for chart in project.ConstCharts.GetAll():
...     name = project.ConstCharts.GetName(chart)
...     rows = project.ConstCharts.GetRows(chart)
...     print(f"Chart: {name} ({len(rows)} rows)")
property ConstChartRows

Access to constituent chart row operations for discourse analysis.

Returns:

Instance providing chart row management methods

Return type:

ConstChartRowOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get a chart
>>> chart = project.ConstCharts.Find("Genesis 1 Analysis")
>>> # Create a row
>>> row = project.ConstChartRows.Create(chart, label="Verse 1")
>>> # Set properties
>>> project.ConstChartRows.SetLabel(row, "Verse 1a")
>>> project.ConstChartRows.SetNotes(row, "Complex structure")
>>> # Get all rows
>>> for row in project.ConstChartRows.GetAll(chart):
...     label = project.ConstChartRows.GetLabel(row)
...     print(f"Row: {label}")
property ConstChartWordGroups

Access to word group operations for constituent chart rows.

Returns:

Instance providing word group management methods

Return type:

ConstChartWordGroupOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get text segments
>>> text = project.Texts.Find("Genesis 1")
>>> para = text.ContentsOA.ParagraphsOS[0]
>>> segments = list(para.SegmentsOS)
>>> # Create word group
>>> row = project.ConstChartRows.Find(chart, 0)
>>> wg = project.ConstChartWordGroups.Create(row, segments[0], segments[2])
>>> # Get all word groups
>>> for wg in project.ConstChartWordGroups.GetAll(row):
...     begin = project.ConstChartWordGroups.GetBeginSegment(wg)
...     print(f"Word group starts at segment {begin.Hvo}")
property ConstChartMovedText

Access to moved text marker operations for constituent charts.

Returns:

Instance providing moved text marker methods

Return type:

ConstChartMovedTextOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get a word group
>>> wg = project.ConstChartWordGroups.Find(row, 0)
>>> # Mark as preposed text
>>> marker = project.ConstChartMovedText.Create(wg, preposed=True)
>>> # Check if preposed
>>> if project.ConstChartMovedText.IsPreposed(marker):
...     print("Text is preposed")
>>> # Get all moved text markers in chart
>>> chart = project.ConstCharts.Find("Genesis 1 Analysis")
>>> for marker in project.ConstChartMovedText.GetAll(chart):
...     wg = project.ConstChartMovedText.GetWordGroup(marker)
...     print(f"Moved text in word group {wg.Hvo}")
property ConstChartMarkers

Access to project-wide chart-marker (CmPossibility) operations.

Markers categorise discourse-chart content (Topic, Focus, …) and live in LangProject.DiscourseDataOA.ChartMarkersOA, shared across every chart in the project.

Returns:

ConstChartMarkerOperations

property ConstChartCellTags

Access to per-cell IConstChartTag operations.

A cell tag is a chart-cell annotation living on IConstChartRow.CellsOS; it references a marker from the project-wide vocabulary via TagRA. Use this surface to annotate cells; use ConstChartMarkers to manage the vocabulary itself.

Returns:

ConstChartCellTagOperations

property ConstChartClauseMarkers

Access to clause marker operations for constituent chart rows.

Returns:

Instance providing clause marker methods

Return type:

ConstChartClauseMarkerOperations

Example

>>> project = FLExProject()
>>> project.OpenProject("MyProject", writeEnabled=True)
>>> # Get a row and word group
>>> row = project.ConstChartRows.Find(chart, 0)
>>> wg = project.ConstChartWordGroups.Find(row, 0)
>>> # Create clause marker
>>> marker = project.ConstChartClauseMarkers.Create(row, wg)
>>> # Add dependent clause
>>> dep_wg = project.ConstChartWordGroups.Find(row, 1)
>>> dep_marker = project.ConstChartClauseMarkers.Create(row, dep_wg)
>>> project.ConstChartClauseMarkers.AddDependentClause(marker, dep_marker)
>>> # Get all markers
>>> for marker in project.ConstChartClauseMarkers.GetAll(row):
...     wg = project.ConstChartClauseMarkers.GetWordGroup(marker)
...     print(f"Clause marker for word group {wg.Hvo}")
property Agent

Alias for Agents (singular form for backward compatibility).

property PossibilityList

Alias for PossibilityLists (singular form for backward compatibility).

property WritingSystem

Alias for WritingSystems (singular form for backward compatibility).

property Overlay

Alias for Overlays (singular form for backward compatibility).

property Publication

Alias for Publications (singular form for backward compatibility).

property TranslationType

Alias for TranslationTypes (singular form for backward compatibility).

property Note

Alias for Notes (singular form for backward compatibility).

ImportLocalizedLists(language_code, progress=None)[source]

Deprecated. Use project.LocalizedLists.Import(language_code).

ImportLocalizedListsForEnabledWS(progress=None)[source]

Deprecated. Use project.LocalizedLists.ImportForAllAnalysisWritingSystems().

property AnnotationDef

Alias for AnnotationDefs (singular form for backward compatibility).

property Check

Alias for Checks (singular form for backward compatibility).

property CustomField

Alias for CustomFields (singular form for backward compatibility).

ProjectName()[source]

Returns the display name of the current project.

BestStr(stringObj)[source]

Generic string function for MultiUnicode and MultiString objects, returning the best analysis or vernacular string.

Note: This method now delegates to WritingSystemOperations for single source of truth.

If a string is passed instead of a multistring object, it is returned as-is with a warning (for backwards compatibility).

UnpackNestedPossibilityList(possibilityList, objClass, flat=False)[source]

Returns a nested or flat list of a Fieldworks possibility list. objClass is the class of object to cast the CmPossibility elements into.

Return items are objects with properties/methods:
  • Hvo - ID (value not the same across projects)

  • Guid - Global Unique ID (same across all projects)

  • ToString() - String representation.

GetAllVernacularWSs()[source]

Returns a set of language tags for all vernacular writing systems used in this project.

Note: This method now delegates to WritingSystemOperations for single source of truth.

GetAllAnalysisWSs()[source]

Returns a set of language tags for all analysis writing systems used in this project.

Note: This method now delegates to WritingSystemOperations for single source of truth.

GetWritingSystems()[source]

Returns the writing systems that are active in this project as a list of tuples: (Name, Language-tag, Handle, IsVernacular). Use the Language-tag when specifying writing system to other functions.

Note: This method now delegates to WritingSystemOperations for single source of truth.

WSUIName(languageTagOrHandle)[source]

Returns the UI name of the writing system for the given language tag or handle. Ignores case and ‘-‘/’_’ differences. Returns None if the language tag is not found.

Note: This method now delegates to WritingSystemOperations for single source of truth.

WSHandle(languageTag)[source]

Returns the handle of the writing system for languageTag. Ignores case and ‘-‘/’_’ differences. Returns None if the language tag is not found.

GetDefaultVernacularWS()[source]

Returns the default vernacular writing system: (Language-tag, Name)

Note: This method now delegates to WritingSystemOperations for single source of truth.

GetDefaultAnalysisWS()[source]

Returns the default analysis writing system: (Language-tag, Name)

Note: This method now delegates to WritingSystemOperations for single source of truth.

GetDefaultVernacularWSHandle()[source]

Returns the default vernacular writing system as a handle (int) suitable for TsStringUtils.MakeString(text, ws) and other multistring accessors.

Sibling to GetDefaultVernacularWS(), which returns a (Language-tag, Name) tuple. Use this method when you need the raw handle for LCM calls; use the tuple-returning method for display.

Returns:

The handle of the default vernacular writing system.

Return type:

int

Example

>>> ws = project.GetDefaultVernacularWSHandle()
>>> tss = TsStringUtils.MakeString("hello", ws)
GetDefaultAnalysisWSHandle()[source]

Returns the default analysis writing system as a handle (int) suitable for TsStringUtils.MakeString(text, ws) and other multistring accessors.

Sibling to GetDefaultAnalysisWS(), which returns a (Language-tag, Name) tuple. Use this method when you need the raw handle for LCM calls; use the tuple-returning method for display.

Returns:

The handle of the default analysis writing system.

Return type:

int

Example

>>> ws = project.GetDefaultAnalysisWSHandle()
>>> tss = TsStringUtils.MakeString("gloss", ws)
GetLinkedFilesDir()[source]

Get the full path to the project’s LinkedFiles directory.

The LinkedFiles directory contains media files organized in subdirectories: - AudioVisual/ - Audio and video files - Pictures/ - Image files - Others/ - Other linked files

Returns:

Absolute path to LinkedFiles directory

Return type:

str

Example

>>> proj = FLExProject()
>>> linked_files = proj.GetLinkedFilesDir()
>>> print(linked_files)
C:\FLExData\MyProject\LinkedFiles

See also

MediaOperations.GetInternalPath() - Get relative path within LinkedFiles MediaOperations.GetExternalPath() - Get full filesystem path

IsAudioWritingSystem(wsHandle)[source]

Check if a writing system is an audio writing system.

Audio writing systems use the special script code “Zxxx” (no written form) and typically have “audio” in their tag. They store audio file paths instead of text content.

Parameters:

wsHandle (int) – Writing system handle to check

Returns:

True if this is an audio writing system, False otherwise

Return type:

bool

Example

>>> ws_handle = proj.WSHandle("en-Zxxx-x-audio")
>>> if proj.IsAudioWritingSystem(ws_handle):
...     print("This is an audio writing system")

See also

GetAudioPath() - Extract audio file path from audio WS field SetAudioPath() - Set audio file path in audio WS field

GetAudioPath(multistring_field, wsHandle)[source]

Extract the audio file path from an audio writing system field.

Audio writing systems embed file paths in ITsString objects using Object Replacement Characters (ORC, U+FFFC) with FwObjDataTypes.kodtExternalPathName.

Parameters:
  • multistring_field – ITsMultiString or similar field containing audio data

  • wsHandle (int) – Audio writing system handle

Returns:

Audio file path, or None if not found

Return type:

str

Example

>>> # Get audio path from allomorph form
>>> form = proj.Allomorph.GetForm(allomorph)
>>> audio_ws = proj.WSHandle("en-Zxxx-x-audio")
>>> audio_path = proj.GetAudioPath(form, audio_ws)
>>> if audio_path:
...     print(f"Audio file: {audio_path}")

See also

IsAudioWritingSystem() - Check if WS is audio type SetAudioPath() - Set audio file path

SetAudioPath(multistring_field, wsHandle, file_path)[source]

Set the audio file path in an audio writing system field.

Embeds the file path using Object Replacement Character (ORC) with FwObjDataTypes.kodtExternalPathName.

Parameters:
  • multistring_field – ITsMultiString or similar field to update

  • wsHandle (int) – Audio writing system handle

  • file_path (str) – Path to audio file (can be relative or absolute)

Example

>>> # Set audio for allomorph form
>>> allomorph = proj.Allomorph.GetAll()[0]
>>> audio_ws = proj.WSHandle("en-Zxxx-x-audio")
>>> audio_path = "LinkedFiles/AudioVisual/hello.wav"
>>> proj.Allomorph.SetFormAudio(allomorph, audio_path, audio_ws)
Raises:

FP_ReadOnlyError – If the project is not opened with writeEnabled=True.

See also

IsAudioWritingSystem() - Check if WS is audio type GetAudioPath() - Get audio file path

GetDateLastModified()[source]
GetPartsOfSpeech()[source]

Returns a list of the parts of speech defined in this project.

Note

This method delegates to POSOperations.GetAll().

GetAllSemanticDomains(recursive=True)[source]

Returns a list of all semantic domains defined in this project. The list is ordered.

Parameters:

recursive (bool) – When True (default), walks the full hierarchy and returns every descendant domain (e.g. ~700+ entries on Sena 3). When False, returns only the top-level domains (~7 entries).

Return items are ICmSemanticDomain objects.

Note

This method delegates to SemanticDomainOperations.GetAll(). The default of recursive=True matches every other GetAll accessor in the codebase (refactor d423e83).

BuildGotoURL(objectOrGuid)[source]

Builds a URL that can be used with os.startfile() to jump to the object in Fieldworks. This method currently supports:

  • Lexical Entries, Senses and any object within the lexicon

  • Wordforms, Analyses and Wordform Glosses

  • Reversal Entries

  • Texts

ObjectRepository(repository)[source]

Returns an object repository. repository is specified by the interface class, such as:

  • ITextRepository

  • ILexEntryRepository

ObjectCountFor(repository)[source]

Returns the number of objects in repository. repository is specified by the interface class, such as:

  • ITextRepository

  • ILexEntryRepository

All repository names can be viewed by opening a project in LCMBrowser, which can be launched via the Help menu. Add “I” to the front and import from SIL.LCModel.

ObjectsIn(repository)[source]

Returns an iterator over all the objects in repository. repository is specified by the interface class, such as:

  • ITextRepository

  • ILexEntryRepository

All repository names can be viewed by opening a project in LCMBrowser, which can be launched via the Help menu. Add “I” to the front and import from SIL.LCModel.

Object(hvoOrGuid)[source]

Returns the CmObject for the given Hvo or guid (str or System.Guid). Refer to .ClassName to determine the LCM class.

LexiconNumberOfEntries()[source]
LexiconAllEntries()[source]

Returns an iterator over all entries in the lexicon.

Each entry is of type:

SIL.LCModel.ILexEntry, which contains:
    - HomographNumber :: integer
    - HomographForm :: string
    - LexemeFormOA ::  SIL.LCModel.IMoForm
         - Form :: SIL.LCModel.MultiUnicodeAccessor
            - GetAlternative : Get String for given WS type
            - SetAlternative : Set string for given WS type
    - SensesOS :: Ordered collection of SIL.LCModel.ILexSense
        - Gloss :: SIL.LCModel.MultiUnicodeAccessor
        - Definition :: SIL.LCModel.MultiStringAccessor
        - SenseNumber :: string
        - ExamplesOS :: Ordered collection of ILexExampleSentence
            - Example :: MultiStringAccessor

Note: This method delegates to LexEntryOperations.GetAll() for single source of truth.

LexiconAllEntriesSorted()[source]

Returns an iterator over all entries in the lexicon sorted by the (lower-case) headword.

LexiconGetHeadword(entry)[source]

Returns the headword for entry.

Note: This method now delegates to LexEntryOperations for single source of truth.

LexiconGetLexemeForm(entry, languageTagOrHandle=None)[source]

Returns the lexeme form for entry in the default vernacular WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to LexEntryOperations for single source of truth.

LexiconSetLexemeForm(entry, form, languageTagOrHandle=None)[source]
Set the lexeme form for entry:
  • form is the new lexeme form string.

  • languageTagOrHandle specifies a non-default writing system.

Note: This method now delegates to LexEntryOperations for single source of truth.

LexiconGetCitationForm(entry, languageTagOrHandle=None)[source]

Returns the citation form for entry in the default vernacular WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to LexEntryOperations for single source of truth.

LexiconGetAlternateForm(entry, languageTagOrHandle=None)[source]

Returns the Alternate form for the entry in the Default Vernacular WS or other WS as specified by languageTagOrHandle.

LexiconGetPublishInCount(entry)[source]

Returns the number of dictionaries that entry is configured to be published in.

LexiconGetPronunciation(pronunciation, languageTagOrHandle=None)[source]

Returns the form for pronunciation in the default vernacular WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to PronunciationOperations for single source of truth.

LexiconGetExample(example, languageTagOrHandle=None)[source]

Returns the example text in the default vernacular WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to ExampleOperations for single source of truth.

LexiconSetExample(example, newString, languageTagOrHandle=None)[source]
Set the default vernacular string for example:
  • newString is the new string value.

  • languageTagOrHandle specifies a non-default writing system.

NOTE: using this function will lose any formatting that might have been present in the example string.

Note: This method now delegates to ExampleOperations for single source of truth.

LexiconGetExampleTranslation(translation, languageTagOrHandle=None)[source]

Returns the translation of an example in the default analysis WS or other WS as specified by languageTagOrHandle.

NOTE: Analysis language translations of example sentences are stored as a collection (list). E.g.:

for translation in example.TranslationsOC:
    print (project.LexiconGetExampleTranslation(translation))

Note: This method works with translation objects (ICmTranslation) directly. For getting translation text from an example object, use Examples.GetTranslation().

LexiconGetSenseNumber(sense)[source]

Returns the sense number for the sense. (This is not available directly from ILexSense.)

Note: This method delegates to LexSenseOperations.GetSenseNumber() for single source of truth.

LexiconGetSenseGloss(sense, languageTagOrHandle=None)[source]

Returns the gloss for the sense in the default analysis WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to LexSenseOperations for single source of truth.

LexiconSetSenseGloss(sense, gloss, languageTagOrHandle=None)[source]
Set the default analysis gloss for sense:
  • gloss is the new gloss string.

  • languageTagOrHandle specifies a non-default writing system.

Note: This method now delegates to LexSenseOperations for single source of truth.

LexiconGetSenseDefinition(sense, languageTagOrHandle=None)[source]

Returns the definition for the sense in the default analysis WS or other WS as specified by languageTagOrHandle.

Note: This method now delegates to LexSenseOperations for single source of truth.

LexiconGetSensePOS(sense)[source]

Returns the part of speech abbreviation for the sense.

Note: This method now delegates to LexSenseOperations for single source of truth.

LexiconGetSenseSemanticDomains(sense)[source]

Returns a list of semantic domain objects belonging to the sense. ToString() and Hvo are available.

Methods available for SemanticDomainsRC:

Count
Add(Hvo)
Contains(Hvo)
Remove(Hvo)
RemoveAll()

Note: This method now delegates to LexSenseOperations for single source of truth.

LexiconEntryAnalysesCount(entry)[source]

Returns a count of the occurrences of the entry in the text corpus.

NOTE: This calculation can produce slightly different results to that shown in FieldWorks (where the same analysis in the same text segment is only counted once in some displays). See LT-13997 for more details.

LexiconSenseAnalysesCount(sense)[source]

Returns a count of the occurrences of the sense in the text corpus.

Note: This method delegates to LexSenseOperations.GetAnalysesCount() for single source of truth.

GetFieldID(className, fieldName)[source]

Return the FieldID (‘flid’) for the given field of an LCM class. className and fieldName are strings, where fieldName may omit the type suffix (e.g. ‘OS’). Both are case-sensitive. For example, find the FieldID for academic domains with:

GetFieldID("LexSense", "DomainTypes")
GetCustomFieldValue(senseOrEntryOrHvo, fieldID, languageTagOrHandle=None)[source]

Returns the field value for String, MultiString, Integer and List (both single and multiple) fields. Raises FP_ParameterError for other field types.

languageTagOrHandle only applies to MultiStrings; if None the best analysis or venacular string is returned.

Note: if the field is a vernacular WS field, then the languageTagOrHandle must be specified.

LexiconFieldIsStringType(fieldID)[source]

Returns True if the given field is a simple string type suitable for use with LexiconAddTagToField(), otherwise returns False.

Delegates to: CustomFields.GetFieldType()

LexiconFieldIsMultiType(fieldID)[source]

Returns True if the given field is a multi string type (MultiUnicode or MultiString)

Delegates to: CustomFields.IsMultiString()

LexiconFieldIsAnyStringType(fieldID)[source]

Returns True if the given field is any of the string types.

Delegates to: CustomFields.GetFieldType()

LexiconGetFieldText(senseOrEntryOrHvo, fieldID, languageTagOrHandle=None)[source]

Return the text value for the given entry/sense and field ID. Provided for use with custom fields. Returns the empty string if the value is null. languageTagOrHandle only applies to MultiStrings; if None the default analysis writing system is returned.

Note: if the field is a vernacular WS field, then languageTagOrHandle must be specified.

For normal fields, the object can be used directly with get_String(). E.g.:

lexForm = lexEntry.LexemeFormOA
lexEntryValue = ITsString(lexForm.Form.get_String(WSHandle)).Text
LexiconSetFieldText(senseOrEntryOrHvo, fieldID, text, languageTagOrHandle=None)[source]

Set the text value for the given entry/sense and field ID. Provided for use with custom fields.

NOTE: writes the string in one writing system only (defaults to the default analysis WS).

For normal fields the object can be used directly with set_String(). E.g.:

lexForm = lexEntry.LexemeFormOA
mkstr = TsStringUtils.MakeString("text to write", WSHandle)
lexForm.Form.set_String(WSHandle, mkstr)
LexiconClearField(senseOrEntryOrHvo, fieldID)[source]

Clears the string field or all of the strings (writing systems) in a multi-string field. Can be used to clear out a custom field.

LexiconSetFieldInteger(senseOrEntryOrHvo, fieldID, integer)[source]

Sets the integer value for the given entry/sense and field ID. Provided for use with custom fields.

LexiconAddTagToField(senseOrEntryOrHvo, fieldID, tag)[source]

Appends the tag string to the end of the given field in the sense or entry inserting a semicolon between tags. If the tag is already in the field then it isn’t added.

ListFieldPossibilityList(senseOrEntry, fieldID)[source]

Return the CmPossibilityList object for the given list field. Raises an exception if the field is not a list (single/Atomic or multiple/Collection)

ListFieldPossibilities(senseOrEntry, fieldID)[source]

Returns the PossibilitiesOS for the given list field. This is a list of CmPossibility objects. Raises an exception if the field is not a list (single/Atomic or multiple/Collection)

Note: this returns the top-level CmPossibility objects. Subitems can be found via the SubPossibilitiesOS attribute. Alternatively, a flat list of all possible options can be obtained with:

options = project.UnpackNestedPossibilityList(possibilities,
                                              str,
                                              True)
ListFieldLookup(senseOrEntry, fieldID, value)[source]

Looks up the value (a string) in the CmPossibilityList for the given field. Returns the CmPossibility object, or None if it can’t be found.

LexiconSetListFieldSingle(senseOrEntry, fieldID, possibilityOrString)[source]

Sets the value for a ‘single’ (Atomic) list field. possibilityOrString can be a CmPossibility object, or a string. A string value can be the full name or the abbreviation (case-sensitive).

Use ListFieldPossibilities() to find the valid values for the list.

Note: this function is primarily for use with custom fields, since regular list field values can be assigned directly. E.g.:

status_poss = project.ListFieldPossibilities(
                  sense,
                  project.GetFieldID("LexSense", "Status"))
sense.StatusRA = status_poss[3]    # Tentative
LexiconClearListFieldSingle(senseOrEntry, fieldID)[source]

Clears the value for a ‘single’ (Atomic) list field.

LexiconSetListFieldMultiple(senseOrEntry, fieldID, listOfValues)[source]

Sets the value(s) for a ‘multiple’ (Collection) list field. listOfValues can be a list of:

  • CmPossibility objects; or

  • CmPossibility hvos; or

  • str (either the full name or the abbreviation; case-sensitive).

Use ListFieldPossibilities() to find the valid values for the list.

Note: this function is primarily for use with custom fields, since regular fields can use the Add(), Remove() and Clear() methods of the field itself (see LcmReferenceCollection).

LexiconGetEntryCustomFields()[source]

Returns a list of the custom fields defined at entry level. Each item in the list is a tuple of (flid, label)

Delegates to: CustomFields.GetAllFields(“LexEntry”)

LexiconGetSenseCustomFields()[source]

Returns a list of the custom fields defined at sense level. Each item in the list is a tuple of (flid, label)

Delegates to: CustomFields.GetAllFields(“LexSense”)

LexiconGetExampleCustomFields()[source]

Returns a list of the custom fields defined at example level. Each item in the list is a tuple of (flid, label)

Delegates to: CustomFields.GetAllFields(“LexExampleSentence”)

LexiconGetAllomorphCustomFields()[source]

Returns a list of the custom fields defined at allomorph level. Each item in the list is a tuple of (flid, label)

Delegates to: CustomFields.GetAllFields(“MoForm”)

LexiconGetEntryCustomFieldNamed(fieldName)[source]

Return the entry-level field ID given its name.

NOTE: fieldName is case-sensitive.

Delegates to: CustomFields.FindField(“LexEntry”, name)

LexiconGetSenseCustomFieldNamed(fieldName)[source]

Return the sense-level field ID given its name.

NOTE: fieldName is case-sensitive.

Delegates to: CustomFields.FindField(“LexSense”, name)

LexiconGetMorphType(entry)[source]

Get the morph type of a lexical entry.

Parameters:

entry – ILexEntry object or HVO

Returns:

The morph type object

Return type:

IMoMorphType

Example

>>> entry = project.LexEntry.Find("run")
>>> morph_type = project.LexiconGetMorphType(entry)
>>> print(morph_type.Name.BestAnalysisAlternative.Text)
stem

Note

Delegates to: LexEntry.GetMorphType(entry)

LexiconSetMorphType(entry, morph_type_or_name)[source]

Set the morph type of a lexical entry.

Parameters:
  • entry – ILexEntry object or HVO

  • morph_type_or_name – IMoMorphType object or name string (“stem”, “root”, “prefix”, “suffix”, etc.)

Example

>>> entry = project.LexEntry.Find("-ing")
>>> project.LexiconSetMorphType(entry, "suffix")

Note

Delegates to: LexEntry.SetMorphType(entry, morph_type_or_name)

LexiconAllAllomorphs()[source]

Get all allomorphs in the entire project.

Yields:

IMoForm – Each allomorph in the project

Example

>>> for allomorph in project.LexiconAllAllomorphs():
...     form = project.Allomorphs.GetForm(allomorph)
...     print(form)

Note

Delegates to: Allomorphs.GetAll()

LexiconNumberOfSenses(entry)[source]

Get the number of senses in a lexical entry.

Parameters:

entry – ILexEntry object or HVO

Returns:

Number of senses

Return type:

int

Example

>>> entry = project.LexEntry.Find("run")
>>> count = project.LexiconNumberOfSenses(entry)
>>> print(f"Entry has {count} senses")

Note

Delegates to: LexEntry.GetSenseCount(entry)

LexiconGetSenseByName(entry, gloss_text, languageTagOrHandle=None)[source]

Find a sense by its gloss text.

Parameters:
  • entry – ILexEntry object or HVO

  • gloss_text (str) – The gloss text to search for

  • languageTagOrHandle – Optional writing system

Returns:

The first sense with matching gloss, or None

Return type:

ILexSense or None

Example

>>> entry = project.LexEntry.Find("run")
>>> sense = project.LexiconGetSenseByName(entry, "to move rapidly")
>>> if sense:
...     print(f"Found sense: {sense.Guid}")

Note

This searches for exact match (case-sensitive). Returns first match if multiple senses have same gloss.

LexiconAddEntry(lexeme_form, morph_type_name='stem', languageTagOrHandle=None)[source]

Create a new lexical entry.

Parameters:
  • lexeme_form (str) – The lexeme form (headword)

  • morph_type_name (str) – Morph type (“stem”, “root”, “prefix”, etc.)

  • languageTagOrHandle – Optional writing system

Returns:

The newly created entry

Return type:

ILexEntry

Example

>>> entry = project.LexiconAddEntry("walk", "stem")
>>> print(project.LexEntry.GetHeadword(entry))
walk

Note

Delegates to: LexEntry.Create(lexeme_form, morph_type_name, wsHandle)

LexiconGetEntry(index)[source]

Get a lexical entry by index.

Parameters:

index (int) – Zero-based index into all entries

Returns:

The entry at the specified index

Return type:

ILexEntry

Example

>>> first_entry = project.LexiconGetEntry(0)
>>> tenth_entry = project.LexiconGetEntry(9)

Warning

Inefficient for large lexicons - iterates through all entries. Consider using LexEntry.Find() or LexEntry.GetAll() instead.

Note

Returns entry in database order (not alphabetical).

LexiconAddSense(entry, gloss, languageTagOrHandle=None)[source]

Add a sense to a lexical entry.

Parameters:
  • entry – ILexEntry object or HVO

  • gloss (str) – The gloss text

  • languageTagOrHandle – Optional writing system

Returns:

The newly created sense

Return type:

ILexSense

Example

>>> entry = project.LexEntry.Find("run")
>>> sense = project.LexiconAddSense(entry, "to move rapidly")

Note

Delegates to: LexEntry.AddSense(entry, gloss, wsHandle)

LexiconGetSense(entry, index)[source]

Get a sense by index from an entry.

Parameters:
  • entry – ILexEntry object or HVO

  • index (int) – Zero-based index

Returns:

The sense at the index, or None if out of range

Return type:

ILexSense or None

Example

>>> entry = project.LexEntry.Find("run")
>>> first_sense = project.LexiconGetSense(entry, 0)
>>> second_sense = project.LexiconGetSense(entry, 1)

Note

Direct access via entry.SensesOS[index] is more efficient.

LexiconDeleteObject(obj)[source]

Delete an object from the database.

Parameters:

obj – The object to delete (ILexEntry, ILexSense, IMoForm, etc.)

Example

>>> sense = entry.SensesOS[0]
>>> project.LexiconDeleteObject(sense)
>>> # Or delete entire entry:
>>> project.LexiconDeleteObject(entry)

Warning

This is a destructive operation and cannot be undone.

Note

Delegates to appropriate Operations class Delete() method based on type.

LexiconGetHeadWord(entry)[source]

Get the headword of an entry.

This is an alias for LexiconGetHeadword() for FlexTools compatibility.

Parameters:

entry – ILexEntry object or HVO

Returns:

The headword

Return type:

str

Example

>>> entry = project.LexEntry.Find("run")
>>> headword = project.LexiconGetHeadWord(entry)
>>> print(headword)
run

Note

Delegates to: LexiconGetHeadword(entry)

LexiconGetAllomorphForms(entry, languageTagOrHandle=None)[source]

Get all allomorph forms for an entry.

Parameters:
  • entry – ILexEntry object or HVO

  • languageTagOrHandle – Optional writing system

Returns:

List of allomorph form strings

Return type:

list

Example

>>> entry = project.LexEntry.Find("run")
>>> forms = project.LexiconGetAllomorphForms(entry)
>>> print(forms)
['run', 'ran', 'runn-']

Note

Returns forms from lexeme form and all alternate forms.

LexiconAddAllomorph(entry, form, morphType, languageTagOrHandle=None)[source]

Add an allomorph to an entry.

Parameters:
  • entry – ILexEntry object or HVO

  • form (str) – The allomorph form

  • morphType – IMoMorphType object or name string

  • languageTagOrHandle – Optional writing system

Returns:

The newly created allomorph

Return type:

IMoForm

Example

>>> entry = project.LexEntry.Find("run")
>>> morph_type = project.LexEntry.GetMorphType(entry)
>>> allomorph = project.LexiconAddAllomorph(entry, "runn-", morph_type)

Note

Delegates to: Allomorphs.Create(entry, form, morphType, wsHandle)

LexiconGetPronunciations(entry)[source]

Get all pronunciations for an entry.

Parameters:

entry – ILexEntry object or HVO

Returns:

Iterator of ILexPronunciation objects

Return type:

iterator

Example

>>> entry = project.LexEntry.Find("run")
>>> for pron in project.LexiconGetPronunciations(entry):
...     form = project.Pronunciations.GetForm(pron)
...     print(form)

Note

Delegates to: Pronunciations.GetAll(entry)

LexiconAddPronunciation(entry, form, languageTagOrHandle=None)[source]

Add a pronunciation to an entry.

Parameters:
  • entry – ILexEntry object or HVO

  • form (str) – The pronunciation form (IPA, etc.)

  • languageTagOrHandle – Optional writing system

Returns:

The newly created pronunciation

Return type:

ILexPronunciation

Example

>>> entry = project.LexEntry.Find("run")
>>> pron = project.LexiconAddPronunciation(entry, "rʌn")

Note

Delegates to: Pronunciations.Create(entry, form, wsHandle)

LexiconGetVariantType(variant)[source]

Get the variant type of a variant entry reference.

Parameters:

variant – ILexEntryRef object

Returns:

The variant type

Return type:

ILexEntryType

Example

>>> for variant_ref in entry.EntryRefsOS:
...     var_type = project.LexiconGetVariantType(variant_ref)
...     if var_type:
...         print(var_type.Name.BestAnalysisAlternative.Text)

Note

Delegates to: Variants.GetVariantType(variant)

LexiconAddVariantForm(entry, form, variant_type, languageTagOrHandle=None)[source]

Add a variant form to an entry.

Parameters:
  • entry – ILexEntry object or HVO

  • form (str) – The variant form

  • variant_type – ILexEntryType object or name string

  • languageTagOrHandle – Optional writing system

Returns:

The newly created variant entry reference

Return type:

ILexEntryRef

Example

>>> entry = project.LexEntry.Find("color")
>>> # This would typically need a variant type from the project
>>> # variant = project.LexiconAddVariantForm(entry, "colour", variant_type)

Note

Delegates to: Variants.Create(entry, form, variant_type, wsHandle)

LexiconGetComplexFormType(entry_ref)[source]

Get the complex form type of an entry reference.

Parameters:

entry_ref – ILexEntryRef object

Returns:

The complex form type

Return type:

ILexEntryType or None

Example

>>> for ref in entry.EntryRefsOS:
...     cf_type = project.LexiconGetComplexFormType(ref)
...     if cf_type:
...         print(cf_type.Name.BestAnalysisAlternative.Text)

Note

Returns None if the entry reference is not a complex form type.

LexiconSetComplexFormType(entry_ref, complex_form_type)[source]

Set the complex form type of an entry reference.

Parameters:
  • entry_ref – ILexEntryRef object

  • complex_form_type – ILexEntryType object

Example

>>> # Get or create complex form type
>>> # cf_type = ... (from project)
>>> # entry_ref = entry.EntryRefsOS[0]
>>> # project.LexiconSetComplexFormType(entry_ref, cf_type)

Note

Replaces any existing complex form types with the specified one.

LexiconAddComplexForm(entry, components, complex_form_type)[source]

Add a complex form entry.

Parameters:
  • entry – ILexEntry - The complex form entry

  • components – list of ILexEntry or ILexSense - The component parts

  • complex_form_type – ILexEntryType - The type of complex form

Returns:

The newly created entry reference

Return type:

ILexEntryRef

Example

>>> # Create a compound "blackboard" from "black" + "board"
>>> blackboard = project.LexEntry.Create("blackboard", "stem")
>>> black = project.LexEntry.Find("black")
>>> board = project.LexEntry.Find("board")
>>> # Would need complex_form_type from project
>>> # ref = project.LexiconAddComplexForm(blackboard, [black, board], cf_type)

Note

Creates an entry reference linking the complex form to its components.

GetLexicalRelationTypes()[source]

Returns an iterator over LexRefType objects, which define a type of lexical relation, such as Part-Whole.

Each LexRefType has:
  • MembersOC: containing zero or more LexReference objects.

  • MappingType: an enumeration defining the type of lexical relation.

LexReference objects have:
  • TargetsRS: the LexSense or LexEntry objects in the relation.

For example:

for lrt in project.GetLexicalRelationTypes():
    if (lrt.MembersOC.Count > 0):
        for lr in lrt.MembersOC:
            for target in lr.TargetsRS:
                if target.ClassName == "LexEntry":
                    # LexEntry
                else:
                    # LexSense

Note

This method delegates to LexReferenceOperations.GetAllTypes().

GetPublications()[source]

Returns a list of the names of the publications defined in the project.

Note

This method delegates to PublicationOperations.GetAll().

PublicationType(publicationName)[source]

Returns the PublicationType object (a CmPossibility) for the given publication name. (A list of publication names can be found using GetPublications().)

Note

This method delegates to PublicationOperations.Find().

TextsNumberOfTexts()[source]

Returns the total number of texts in the project.

Note: This method delegates to TextOperations.GetAll() for single source of truth.

TextsGetAll(supplyName=True, supplyText=True)[source]

A generator that returns all the texts in the project as tuples of (name, text) where:

  • name is the best vernacular or analysis name.

  • text is a string with newlines separating paragraphs.

Passing supplyName/Text = False returns only the texts or names.

Note: This method now delegates to TextOperations.GetAll() for retrieving texts.

flexicon.code.PythonicWrapper module

Pythonic Wrapper for LibLCM Objects

LibLCM uses 2-character suffixes to indicate relationship types:
  • OA: Owning Atomic (single owned child)

  • OS: Owning Sequence (ordered collection of owned children)

  • OC: Owning Collection (unordered collection of owned children)

  • RA: Reference Atomic (single reference)

  • RS: Reference Sequence (ordered collection of references)

  • RC: Reference Collection (unordered collection of references)

This wrapper allows Python code to use suffix-free names:
  • entry.Senses instead of entry.SensesOS

  • entry.LexemeForm instead of entry.LexemeFormOA

  • sense.SemanticDomains instead of sense.SemanticDomainsRC

Usage:

from flexlibs2.code.PythonicWrapper import wrap, unwrap

# Wrap an LCM object
entry = wrap(raw_entry)

# Now use pythonic names
for sense in entry.Senses:      # Resolves to SensesOS
    print(sense.Gloss)          # Resolves to Gloss (no suffix needed)

# Unwrap to get original object
raw = unwrap(entry)

# Or use the p() shorthand
from flexlibs2.code.PythonicWrapper import p
for sense in p(entry).Senses:
    print(p(sense).Gloss)
class flexicon.code.PythonicWrapper.PythonicWrapper(obj)[source]

Bases: object

Wrapper that provides suffix-free property access to LibLCM objects.

Uses __getattr__ to intercept attribute access and try suffixed variants when the base name isn’t found.

Example:

wrapped = PythonicWrapper(entry)
for sense in wrapped.Senses:  # Tries SensesOS, SensesOC, etc.
    text = wrapped.Gloss      # Returns Gloss directly if it exists
flexicon.code.PythonicWrapper.wrap(obj)[source]

Wrap an LCM object for pythonic property access.

Parameters:

obj – LibLCM object (ILexEntry, ILexSense, etc.)

Returns:

Wrapped object with suffix-free property access

Return type:

PythonicWrapper

Example:

entry = wrap(raw_entry)
for sense in entry.Senses:  # Uses SensesOS internally
    print(sense)
flexicon.code.PythonicWrapper.unwrap(obj)[source]

Get the underlying LCM object from a wrapper.

Parameters:

obj – PythonicWrapper or raw LCM object

Returns:

The underlying LCM object

Example:

raw = unwrap(wrapped_entry)
flexicon.code.PythonicWrapper.p(obj)

Wrap an LCM object for pythonic property access.

Parameters:

obj – LibLCM object (ILexEntry, ILexSense, etc.)

Returns:

Wrapped object with suffix-free property access

Return type:

PythonicWrapper

Example:

entry = wrap(raw_entry)
for sense in entry.Senses:  # Uses SensesOS internally
    print(sense)

flexicon.code.exceptions module

FLExProject exception hierarchy for error handling and reporting.

exception flexicon.code.exceptions.FP_ProjectError(message)[source]

Bases: Exception

Exception raised for any problems opening the project.

Variables:

error (- message -- explanation of the)

exception flexicon.code.exceptions.FP_FileNotFoundError(projectName, e)[source]

Bases: FP_ProjectError

exception flexicon.code.exceptions.FP_FileLockedError[source]

Bases: FP_ProjectError

exception flexicon.code.exceptions.FP_MigrationRequired[source]

Bases: FP_ProjectError

exception flexicon.code.exceptions.FP_RuntimeError(message)[source]

Bases: Exception

Exception raised for any problems running the module.

Variables:

error (- message -- explanation of the)

exception flexicon.code.exceptions.FP_ReadOnlyError[source]

Bases: FP_RuntimeError

exception flexicon.code.exceptions.FP_WritingSystemError(writingSystemName)[source]

Bases: FP_RuntimeError

exception flexicon.code.exceptions.FP_NullParameterError[source]

Bases: FP_RuntimeError

exception flexicon.code.exceptions.FP_ParameterError(msg)[source]

Bases: FP_RuntimeError

exception flexicon.code.exceptions.FP_TransactionError(message)[source]

Bases: FP_RuntimeError

flexicon.code.lcm_casting module

LCM Object Casting Utilities for pythonnet. import logging

This module provides utilities for casting LCM objects from their base interface types to their concrete derived interfaces. This is necessary because pythonnet respects .NET interface typing strictly.

The Problem:

When you iterate over a collection like MorphoSyntaxAnalysesOC, pythonnet returns objects typed as the base interface (IMoMorphSynAnalysis). Properties from derived interfaces like IMoStemMsa.PartOfSpeechRA are not accessible until you explicitly cast the object to its concrete interface type.

For example:

# This will NOT work - msa is typed as IMoMorphSynAnalysis
for msa in entry.MorphoSyntaxAnalysesOC:
    pos = msa.PartOfSpeechRA  # AttributeError - property not found!

# This WILL work - cast to concrete type first
for msa in entry.MorphoSyntaxAnalysesOC:
    concrete_msa = cast_to_concrete(msa)
    if hasattr(concrete_msa, 'PartOfSpeechRA'):
        pos = concrete_msa.PartOfSpeechRA  # Works!
Why This Happens:

In .NET, IMoStemMsa inherits from IMoMorphSynAnalysis. When you access a collection typed as IEnumerable<IMoMorphSynAnalysis>, the CLR returns objects as the interface type, not the concrete class. Pythonnet cannot automatically determine the derived interface type - you must cast explicitly.

Usage:

from flexlibs2.code.lcm_casting import cast_to_concrete, get_pos_from_msa

# Cast any LCM object to its concrete interface
for msa in entry.MorphoSyntaxAnalysesOC:
    concrete = cast_to_concrete(msa)
    print(f"Class: {msa.ClassName}, Type: {type(concrete)}")

# Convenience function for the common POS lookup pattern
for msa in entry.MorphoSyntaxAnalysesOC:
    pos = get_pos_from_msa(msa)
    if pos:
        print(f"Part of Speech: {pos.Name.BestAnalysisAlternative.Text}")
Supported Types:
  • MSA types: MoStemMsa, MoDerivAffMsa, MoInflAffMsa, MoUnclassifiedAffixMsa

  • Allomorph types: MoStemAllomorph, MoAffixAllomorph

  • Phonological rule types: PhRegularRule, PhMetathesisRule, PhReduplicationRule

  • Compound rule types: MoEndoCompound, MoExoCompound

  • Morphosyntactic prohibition types: MoAdhocProhibGr, MoAdhocProhibMorph, MoAdhocProhibAllomorph

  • Owner / container types (used by .Owner casting paths in Lexicon, Notebook, and Discourse operations): LexEntry, LexSense, RnGenericRec, CmPossibility, CmAnthroItem, DsConstChart, Text, StText, StTxtPara

Note

The interface cache is lazy-loaded on first use to avoid import issues at module load time. This is important because SIL.LCModel may not be available until after FLExInit has run.

flexicon.code.lcm_casting.cast_to_concrete(obj)[source]

Cast an LCM object to its concrete interface type based on ClassName.

This function examines the object’s ClassName property and casts it to the appropriate derived interface type. If the ClassName is not in the known mappings, the original object is returned unchanged.

Parameters:

obj – An LCM object with a ClassName property (e.g., IMoMorphSynAnalysis, IMoForm, or any ICmObject).

Returns:

The object cast to its concrete interface type, or the original object if the ClassName is not recognized or casting fails.

Example:

# Iterate MSAs and access derived properties
for msa in entry.MorphoSyntaxAnalysesOC:
    concrete_msa = cast_to_concrete(msa)

    # Now we can check for and access derived properties
    if hasattr(concrete_msa, 'PartOfSpeechRA'):
        pos = concrete_msa.PartOfSpeechRA
        if pos:
            print(f"POS: {pos.Name.BestAnalysisAlternative.Text}")

# Cast allomorphs to access type-specific properties
for allo in entry.AlternateFormsOS:
    concrete_allo = cast_to_concrete(allo)

    if hasattr(concrete_allo, 'StemName'):
        # This is a stem allomorph
        stem_name = concrete_allo.StemName
    elif hasattr(concrete_allo, 'InflectionClasses'):
        # This is an affix allomorph
        infl_classes = concrete_allo.InflectionClasses

Notes

  • Returns the original object if ClassName is not in the mapping

  • Returns the original object if casting fails for any reason

  • Thread-safe for the interface loading (uses lazy initialization)

  • The interface cache is loaded on first call

flexicon.code.lcm_casting.get_pos_from_msa(msa)[source]

Get the Part of Speech from any MSA type.

This is a convenience function for the common pattern of extracting the Part of Speech reference from a MorphoSyntaxAnalysis object. It handles the casting internally and checks each MSA type for its POS property.

Different MSA types store POS in different properties:
  • MoStemMsa: PartOfSpeechRA (main POS for stems)

  • MoDerivAffMsa: ToPartOfSpeechRA (output POS after derivation)

  • MoInflAffMsa: PartOfSpeechRA (POS this affix attaches to)

  • MoUnclassifiedAffixMsa: PartOfSpeechRA

Parameters:

msa – An MSA object (IMoMorphSynAnalysis or derived type).

Returns:

The Part of Speech reference, or None if:
  • The MSA type doesn’t have a POS property

  • The POS property is not set (null reference)

  • The object cannot be cast to a known MSA type

Return type:

IPartOfSpeech

Example:

# Get POS for all MSAs on an entry
for msa in entry.MorphoSyntaxAnalysesOC:
    pos = get_pos_from_msa(msa)
    if pos:
        pos_name = pos.Name.BestAnalysisAlternative.Text
        pos_abbr = pos.Abbreviation.BestAnalysisAlternative.Text
        print(f"{pos_name} ({pos_abbr})")

# Check if entry has a specific POS
target_pos_guid = some_guid
has_target_pos = any(
    get_pos_from_msa(msa) and
    str(get_pos_from_msa(msa).Guid) == str(target_pos_guid)
    for msa in entry.MorphoSyntaxAnalysesOC
)

Notes

  • For MoDerivAffMsa, this returns ToPartOfSpeechRA (the output POS), not FromPartOfSpeechRA (the input POS). Use cast_to_concrete() directly if you need to access FromPartOfSpeechRA.

  • Returns None rather than raising exceptions for robustness

  • Handles all common MSA types found in typical FLEx projects

flexicon.code.lcm_casting.clone_properties(source_obj, dest_obj, project=None)[source]

Deep clone all properties from source object to destination object.

This is a Python equivalent of ICloneableCmObject.SetCloneProperties() from C#. It copies all properties recursively, handling: - Simple properties (names, descriptions, etc.) - Reference properties (RA) - Owned objects (OA) - creates new objects with cloned properties - Owned collections (OS/OC) - creates new objects for each item

Parameters:
  • source_obj – The source LCM object to clone from.

  • dest_obj – The destination LCM object to clone to.

  • project – Optional FLExProject instance for factory access. If not provided, extracted from the destination object’s owner.

Returns:

None. The destination object is modified in place.

Example:

from flexlibs2.code.lcm_casting import clone_properties

# Clone a rule
source_rule = phonRuleOps.GetAll()[0]
new_rule = factory.Create()
clone_properties(source_rule, new_rule, project)

Notes

  • Recursively clones owned objects

  • Shares reference objects (doesn’t create copies of referenced objects)

  • Handles collections by adding cloned items to the destination collection

  • Silently skips any properties that cannot be cloned

flexicon.code.lcm_casting.cast_phonological_rule(rule_obj)[source]

Cast a phonological rule to its concrete interface type.

Phonological rules come back from GetAll() typed as IPhSegmentRule (base interface). This function casts to the concrete interface based on ClassName: - PhRegularRule -> IPhRegularRule - PhMetathesisRule -> IPhMetathesisRule - PhReduplicationRule -> IPhReduplicationRule

Parameters:

rule_obj – A phonological rule object (typed as IPhSegmentRule or similar).

Returns:

The rule cast to its concrete interface, or the original object if not recognized.

Example:

from flexlibs2.code.lcm_casting import cast_phonological_rule

# Get rules and cast them
for rule in phonRuleOps.GetAll():
    concrete_rule = cast_phonological_rule(rule)

    # Now can access type-specific properties
    if concrete_rule.ClassName == 'PhRegularRule':
        rhs_count = concrete_rule.RightHandSidesOS.Count
flexicon.code.lcm_casting.validate_merge_compatibility(survivor_obj, victim_obj)[source]

Validate that two objects can be safely merged.

Checks that both objects are of the same class and, for objects with multiple concrete implementations, that they have the same concrete type. This prevents merging incompatible types (e.g., PhRegularRule into PhMetathesisRule).

Parameters:
  • survivor_obj – The object that will receive merged data.

  • victim_obj – The object that will be deleted/merged into survivor.

Returns:

(is_compatible, error_message)
  • (True, “”) if merge is safe

  • (False, error_message) if merge should be blocked

Return type:

tuple

Example:

from flexlibs2.code.lcm_casting import validate_merge_compatibility

# Validate before merging
is_ok, msg = validate_merge_compatibility(entry1, entry2)
if not is_ok:
    raise FP_ParameterError(msg)

# Works for all object types
is_ok, msg = validate_merge_compatibility(rule1, rule2)
is_ok, msg = validate_merge_compatibility(sense1, sense2)

Notes

  • Both objects must have a ClassName attribute

  • For types with multiple concrete implementations (like phonological rules), both must have the same ClassName (e.g., both PhRegularRule)

  • For other types, same ClassName is sufficient

  • Prevents data corruption from merging incompatible object types

flexicon.code.lcm_casting.get_from_pos_from_msa(msa)[source]

Get the source Part of Speech from a derivational MSA.

Only IMoDerivAffMsa has a FromPartOfSpeechRA property indicating the POS before derivation. This function returns None for all other MSA types.

Parameters:

msa – An MSA object (IMoMorphSynAnalysis or derived type).

Returns:

The source Part of Speech for derivational affixes,

or None if not a derivational MSA or no source POS is set.

Return type:

IPartOfSpeech

Example:

for msa in entry.MorphoSyntaxAnalysesOC:
    from_pos = get_from_pos_from_msa(msa)
    to_pos = get_pos_from_msa(msa)
    if from_pos and to_pos:
        from_name = from_pos.Name.BestAnalysisAlternative.Text
        to_name = to_pos.Name.BestAnalysisAlternative.Text
        print(f"Derives: {from_name} -> {to_name}")

Notes

  • Only meaningful for MoDerivAffMsa objects

  • Returns None for MoStemMsa, MoInflAffMsa, MoUnclassifiedAffixMsa

  • Use in combination with get_pos_from_msa() to get both ends of a derivational relationship

flexicon.code.lcm_casting.get_common_properties(objects)[source]

Find properties that are available on ALL objects in a list.

When working with collections of objects that may have different concrete types (e.g., mixed phonological rules), this function identifies which properties are safely accessible on all objects without type checking.

This is useful for implementing filtering or display logic that works uniformly across all types.

Parameters:

objects – Iterable of LCM objects (all should have ClassName attribute).

Returns:

Property names that exist on ALL objects. Empty set if no common properties or if input is empty.

Return type:

set

Example:

from flexlibs2.code.lcm_casting import get_common_properties

# Find properties available on all rule types
rules = phonRuleOps.GetAll()
common = get_common_properties(rules)
print(common)  # {'Name', 'Direction', 'StrucDescOS', ...}

# These properties can be accessed safely on any rule
for rule in rules:
    name = rule.Name
    direction = rule.Direction

Notes

  • Properties starting with ‘_’ are excluded

  • Callable attributes (methods) are excluded

  • Returns intersection of properties across all objects

  • Empty list returns empty set (no intersection with all)

  • Useful before implementing collection-wide filters

flexicon.code.lcm_casting.get_concrete_type_properties(lcm_obj)[source]

Get properties that are unique to an object’s concrete type.

When you have an LCM object typed as a base interface (e.g., IPhSegmentRule), this function identifies which properties are specific to its concrete type (e.g., RightHandSidesOS for PhRegularRule).

This is useful for introspection and for determining what type-specific capabilities an object has.

Parameters:

lcm_obj – An LCM object with a ClassName attribute.

Returns:

Mapping of property names to their values, containing only properties on the concrete type that don’t exist on a simple interface comparison. Empty dict if no unique properties.

Return type:

dict

Example:

from flexlibs2.code.lcm_casting import get_concrete_type_properties

# Get type-specific properties for a rule
rule = phonRuleOps.GetAll()[0]
unique_props = get_concrete_type_properties(rule)

if rule.ClassName == 'PhRegularRule':
    print('RightHandSidesOS' in unique_props)  # True
    print(unique_props['RightHandSidesOS'])  # The actual RHS collection

if rule.ClassName == 'PhMetathesisRule':
    print('LeftPartOfMetathesisOS' in unique_props)  # True

Notes

  • Returns empty dict if object has no ClassName attribute

  • Properties are returned as property_name -> value mappings

  • Private attributes (starting with _) are excluded

  • Callable attributes (methods) are excluded

  • Use with get_common_properties() to understand type diversity

flexicon.code.transaction module

flexicon.code.undoable_operation module

Module contents