flexicon.code package¶
Subpackages¶
- flexicon.code.Discourse package
- Submodules
- flexicon.code.Discourse.ConstChartCellTagOperations module
- flexicon.code.Discourse.ConstChartClauseMarkerOperations module
- flexicon.code.Discourse.ConstChartMarkerOperations module
- flexicon.code.Discourse.ConstChartMovedTextOperations module
- flexicon.code.Discourse.ConstChartOperations module
- flexicon.code.Discourse.ConstChartRowOperations module
- flexicon.code.Discourse.ConstChartWordGroupOperations module
- Module contents
- flexicon.code.Grammar package
- Submodules
- flexicon.code.Grammar.EnvironmentOperations module
- flexicon.code.Grammar.GramCatOperations module
- flexicon.code.Grammar.InflectionFeatureOperations module
InflectionFeatureOperationsCATALOG_FILECATALOG_SUBDIRCATALOG_PARSER()CATALOG_PREFIX_WRITEDOMAIN_LABELInflectionClassGetAll()InflectionClassCreate()InflectionClassDelete()InflectionClassGetName()InflectionClassSetName()FeatureStructureGetAll()FeatureStructureCreate()FeatureStructureDelete()FeatureGetAll()Find()Exists()TypeFind()TypeCreate()Create()CreateValue()CreateClosedFeatureWithValues()MakeFeatStruc()DescribeFeatStruc()FeatureCreate()FeatureDelete()FeatureGetValues()GetFeatures()GetFeatureConstraints()GetTypes()GetSyncableProperties()ApplySyncableProperties()CompareTo()
- flexicon.code.Grammar.MorphRuleOperations module
MorphRuleOperationsGetAll()GetAllCompoundRules()GetAllAffixTemplates()GetAllAffixTemplatesForPOS()GetAllAdhocCoProhibitions()CreateCompoundRule()CreateAffixTemplate()AddSlotToTemplate()Delete()GetName()SetName()GetDescription()SetDescription()GetStratum()SetStratum()IsDisabled()SetDisabled()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()
- flexicon.code.Grammar.NaturalClassOperations module
- flexicon.code.Grammar.POSOperations module
POSOperationsCATALOG_FILECATALOG_SUBDIRCATALOG_PARSER()CATALOG_PREFIX_WRITEDOMAIN_LABELGetAll()Create()Delete()Exists()Find()GetName()SetName()GetAbbreviation()SetAbbreviation()GetSubcategories()GetParent()AddSubcategory()RemoveSubcategory()GetCatalogSourceId()GetInflectionClasses()GetAffixSlots()CreateAffixSlot()GetSlotName()SetSlotName()IsSlotOptional()SetSlotOptional()GetAffixesInSlot()GetEntryCount()Duplicate()GetSyncableProperties()ApplySyncableProperties()GetDefaultFeatures()SetDefaultFeatures()GetInherFeatVal()SetInherFeatVal()CompareTo()
- flexicon.code.Grammar.PhonFeatureOperations module
PhonFeatureOperationsCATALOG_FILECATALOG_SUBDIRCATALOG_PARSER()CATALOG_PREFIX_WRITEDOMAIN_LABELGetAll()GetName()GetAbbreviation()GetDescription()GetValues()Find()Exists()Create()SetName()SetAbbreviation()SetDescription()Delete()CreateValue()DeleteValue()MakeFeatStruc()GetSyncableProperties()ApplySyncableProperties()
- flexicon.code.Grammar.PhonemeOperations module
PhonemeOperationsGetAll()Create()Delete()Duplicate()Exists()Find()GetName()GetRepresentation()SetRepresentation()GetDescription()SetDescription()GetFeatures()GetCodes()AddCode()RemoveCode()FindCode()ReplaceCode()GetBasicIPASymbol()SetBasicIPASymbol()IsVowel()IsConsonant()GetSyncableProperties()ApplySyncableProperties()CompareTo()ImportCatalog()
- flexicon.code.Grammar.PhonologicalRuleOperations module
PhonologicalRuleOperationsGetAll()Create()Delete()Exists()Find()GetName()SetName()GetDescription()SetDescription()GetStratum()SetStratum()GetDirection()SetDirection()SetLeftContext()SetRightContext()MakeConstraint()DeleteConstraint()GetConstraints()WireRule()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()
- flexicon.code.Grammar.StratumOperations module
- flexicon.code.Grammar.adhoc_prohibition module
- flexicon.code.Grammar.affix_slot module
- flexicon.code.Grammar.affix_template module
- flexicon.code.Grammar.affix_template_collection module
- flexicon.code.Grammar.compound_rule module
- flexicon.code.Grammar.compound_rule_collection module
- flexicon.code.Grammar.phonological_rule module
- flexicon.code.Grammar.prohibition_collection module
- flexicon.code.Grammar.rule_collection module
- Module contents
- flexicon.code.Lexicon package
- Submodules
- flexicon.code.Lexicon.AllomorphOperations module
- flexicon.code.Lexicon.EtymologyOperations module
EtymologyOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()Reorder()GetSource()SetSource()GetForm()SetForm()GetGloss()SetGloss()GetComment()SetComment()GetBibliography()SetBibliography()GetOwningEntry()GetGuid()GetLanguages()SetLanguages()GetLanguage()SetLanguage()
- flexicon.code.Lexicon.ExampleOperations module
ExampleOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()Reorder()GetExample()SetExample()GetTranslations()GetTranslation()SetTranslation()AddTranslation()RemoveTranslation()GetReference()SetReference()GetMediaFiles()GetMediaCount()AddMediaFile()RemoveMediaFile()MoveMediaFile()GetOwningSense()GetGuid()GetLiteralTranslation()SetLiteralTranslation()GetDoNotPublishIn()AddDoNotPublishIn()RemoveDoNotPublishIn()
- flexicon.code.Lexicon.LexEntryOperations module
LexEntryOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()Exists()Find()GetHeadword()SetHeadword()GetLexemeForm()SetLexemeForm()GetCitationForm()SetCitationForm()GetBestVernacularAlternative()GetShortName()GetLongName()GetLIFTid()GetHomographNumber()SetHomographNumber()GetDateCreated()GetDateModified()GetMorphType()SetMorphType()GetAvailableMorphTypes()ValidateMorphType()GetAllByMorphType()GetSenses()GetSenseCount()AddSense()GetGuid()GetImportResidue()SetImportResidue()GetBibliography()SetBibliography()GetComment()SetComment()GetLiteralMeaning()SetLiteralMeaning()GetRestrictions()SetRestrictions()GetSummaryDefinition()SetSummaryDefinition()GetDoNotUseForParsing()SetDoNotUseForParsing()GetExcludeAsHeadword()SetExcludeAsHeadword()GetDoNotPublishIn()AddDoNotPublishIn()RemoveDoNotPublishIn()GetDoNotShowMainEntryIn()AddDoNotShowMainEntryIn()RemoveDoNotShowMainEntryIn()GetVisibleComplexFormBackRefs()GetComplexFormsNotSubentries()GetMinimalLexReferences()GetAllSenses()GetAllComplexFormTypes()FindComplexFormType()AddComplexFormComponent()RemoveComplexFormComponent()GetComplexFormComponents()MergeObject()
- flexicon.code.Lexicon.LexReferenceOperations module
LexRefMappingTypesLexReferenceOperationsGetAllTypes()CreateType()DeleteType()FindType()GetTypeName()SetTypeName()GetTypeReverseName()SetTypeReverseName()GetMappingType()GetAll()Create()Delete()GetTargets()AddTarget()RemoveTarget()GetType()GetReferencesOfType()ShowComplexFormsIn()GetComplexFormEntries()GetComponentEntries()GetSyncableProperties()ApplySyncableProperties()CompareTo()
- flexicon.code.Lexicon.LexSenseOperations module
LexSenseOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()Reorder()Find()GetGloss()SetGloss()GetDefinition()SetDefinition()GetDefinitionOrGloss()GetMSA()GetPartOfSpeech()GetPartOfSpeechObject()SetPartOfSpeech()GetGrammaticalInfo()SetGrammaticalInfo()GetSemanticDomains()AddSemanticDomain()RemoveSemanticDomain()GetExamples()GetExampleCount()AddExample()GetSubsenses()CreateSubsense()GetParentSense()GetStatus()SetStatus()GetSenseType()SetSenseType()GetReversalEntries()GetReversalCount()GetPictures()GetPictureCount()AddPicture()RemovePicture()MovePicture()SetCaption()GetCaption()RenamePicture()GetGuid()GetOwningEntry()GetSenseNumber()GetAnalysesCount()GetBibliography()SetBibliography()GetGeneralNote()SetGeneralNote()GetDiscourseNote()SetDiscourseNote()GetEncyclopedicInfo()SetEncyclopedicInfo()GetGrammarNote()SetGrammarNote()GetPhonologyNote()SetPhonologyNote()GetSemanticsNote()SetSemanticsNote()GetSocioLinguisticsNote()SetSocioLinguisticsNote()GetAnthroNote()SetAnthroNote()GetRestrictions()SetRestrictions()GetSource()SetSource()GetScientificName()SetScientificName()GetImportResidue()SetImportResidue()GetUsageTypes()AddUsageType()RemoveUsageType()GetDomainTypes()AddDomainType()RemoveDomainType()GetAnthroCodes()AddAnthroCode()RemoveAnthroCode()GetDoNotPublishIn()AddDoNotPublishIn()RemoveDoNotPublishIn()GetVisibleComplexFormBackRefs()GetComplexFormsNotSubentries()GetMinimalLexReferences()GetAllSenses()MergeObject()
- flexicon.code.Lexicon.MSAOperations module
RemovedMSAEntryOrphanBreakdownRemoveOrphanedResultMSAOperationsGetAll()CreateStem()CreateDerivAff()CreateInflAff()CreateUnclassifiedAffix()SetStemMsaPos()SetDerivAffMsaPos()SetInflAffMsaSlots()GetInflAffMsaSlots()GetStemFeatures()GetInflAffFeatures()GetDerivFromFeatures()GetDerivToFeatures()GetFeatures()ChangeAffixVariant()RemoveOrphaned()GetSyncableProperties()ApplySyncableProperties()
- flexicon.code.Lexicon.PronunciationOperations module
- flexicon.code.Lexicon.SemanticDomainOperations module
SemanticDomainOperationsCATALOG_FILECATALOG_SUBDIRLCM_FIELD_NAMELANG_PROJECT_LIST_ATTRDOMAIN_ITEM_LABEL_SINGULARDOMAIN_ITEM_LABEL_PLURALGetAll()Find()FindByName()Exists()GetName()SetName()GetDescription()SetDescription()GetAbbreviation()GetNumber()GetQuestions()GetOcmCodes()GetSubdomains()GetParent()GetDepth()GetSensesInDomain()GetSenseCount()Create()Delete()Duplicate()ImportCatalog()GetSyncableProperties()CompareTo()
- flexicon.code.Lexicon.VariantOperations module
- flexicon.code.Lexicon.allomorph module
- flexicon.code.Lexicon.allomorph_collection module
- flexicon.code.Lexicon.morphosyntax_analysis module
- flexicon.code.Lexicon.msa_collection module
- Module contents
- flexicon.code.Lists package
- Submodules
- flexicon.code.Lists.AgentOperations module
- flexicon.code.Lists.ConfidenceOperations module
- flexicon.code.Lists.LocalizedListsOperations module
- flexicon.code.Lists.OverlayOperations module
OverlayOperationsGetAll()Create()Delete()Find()Exists()GetName()SetName()Duplicate()GetDescription()SetDescription()GetGuid()CompareTo()GetSyncableProperties()IsVisible()SetVisible()GetDisplayOrder()SetDisplayOrder()GetElements()AddElement()RemoveElement()GetChart()GetPossItems()FindByChart()GetVisibleOverlays()
- flexicon.code.Lists.PossibilityListOperations module
PossibilityListOperationsGetAllLists()CreateList()DeleteList()FindList()CreateItemInListByName()GetListName()SetListName()GetItems()CreateItem()DeleteItem()Duplicate()GetSyncableProperties()CompareTo()FindItem()GetItemName()SetItemName()GetItemAbbreviation()SetItemAbbreviation()GetItemDescription()SetItemDescription()GetSubitems()GetParentItem()MoveItem()GetDepth()GetListGuid()GetItemGuid()GetItemHvo()GetListHvo()
- flexicon.code.Lists.PublicationOperations module
- flexicon.code.Lists.TranslationTypeOperations module
- flexicon.code.Lists.possibility_item_base module
- Module contents
- flexicon.code.Notebook package
- Submodules
- flexicon.code.Notebook.AnthropologyOperations module
AnthropologyOperationsCATALOG_FILEFRAME_CATALOG_FILECATALOG_SUBDIRLCM_FIELD_NAMELANG_PROJECT_LIST_ATTRDOMAIN_ITEM_LABEL_SINGULARDOMAIN_ITEM_LABEL_PLURALGetAll()Create()CreateSubitem()Delete()Exists()Find()FindByCode()FindByCategory()GetName()SetName()GetAbbreviation()SetAbbreviation()GetDescription()SetDescription()GetAnthroCode()SetAnthroCode()GetCategory()SetCategory()GetSubitems()GetParent()GetTexts()AddText()RemoveText()GetTextCount()GetItemsForText()GetResearchers()AddResearcher()RemoveResearcher()Duplicate()ImportCatalog()ImportFrameCatalog()GetSyncableProperties()CompareTo()GetGuid()GetDateCreated()GetDateModified()
- flexicon.code.Notebook.DataNotebookOperations module
DataNotebookOperationsGetAll()Create()Delete()Exists()Find()GetTitle()SetTitle()GetContent()SetContent()GetRecordType()SetRecordType()GetAllRecordTypes()FindRecordTypeByName()GetDateCreated()GetDateModified()GetDateOfEvent()SetDateOfEvent()GetSubRecords()CreateSubRecord()GetParentRecord()GetResearchers()AddResearcher()RemoveResearcher()GetParticipants()AddParticipant()RemoveParticipant()GetLocations()AddLocation()RemoveLocation()GetSources()AddSource()RemoveSource()GetTexts()LinkToText()UnlinkFromText()GetMediaFiles()AddMediaFile()RemoveMediaFile()GetStatus()SetStatus()GetAllStatuses()FindStatusByName()FindByDate()FindByResearcher()FindByType()Duplicate()GetSyncableProperties()CompareTo()GetGuid()GetConfidence()SetConfidence()
- flexicon.code.Notebook.LocationOperations module
LocationOperationsGetAll()Create()Delete()Find()Exists()GetName()SetName()GetAlias()SetAlias()GetCoordinates()SetCoordinates()GetElevation()SetElevation()GetDescription()SetDescription()GetRegion()SetRegion()GetSublocations()CreateSublocation()Duplicate()GetSyncableProperties()CompareTo()GetGuid()GetDateCreated()GetDateModified()FindByCoordinates()GetNearby()
- flexicon.code.Notebook.NoteOperations module
- flexicon.code.Notebook.PersonOperations module
PersonOperationsGetAll()Create()Delete()Exists()Find()GetName()SetName()GetGender()SetGender()GetDateOfBirth()SetDateOfBirth()GetEmail()SetEmail()GetPhone()SetPhone()GetAddress()SetAddress()GetEducation()SetEducation()GetPositions()AddPosition()Duplicate()GetSyncableProperties()CompareTo()GetGuid()GetDateCreated()GetDateModified()GetResidences()AddResidence()GetLanguages()AddLanguage()GetNotes()AddNote()
- flexicon.code.Notebook.annotation module
- flexicon.code.Notebook.annotation_collection module
- Module contents
- flexicon.code.Parser package
- flexicon.code.Reversal package
- flexicon.code.Scripture package
- Submodules
- flexicon.code.Scripture.ScrAnnotationsOperations module
- flexicon.code.Scripture.ScrBookOperations module
- flexicon.code.Scripture.ScrDraftOperations module
- flexicon.code.Scripture.ScrNoteOperations module
- flexicon.code.Scripture.ScrSectionOperations module
- flexicon.code.Scripture.ScrTxtParaOperations module
- Module contents
- flexicon.code.Shared package
- Submodules
- flexicon.code.Shared.FilterOperations module
- flexicon.code.Shared.MediaOperations module
MediaTypeMediaOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()CompareTo()Find()Exists()GetInternalPath()GetExternalPath()SetInternalPath()RenameMediaFile()GetLabel()SetLabel()GetMediaType()IsAudio()IsVideo()IsImage()GetOwners()GetOwnerCount()CopyToProject()IsValid()GetGuid()GetHvo()GetFileSize()GetAllByType()GetOrphanedMedia()
- flexicon.code.Shared.catalog module
- flexicon.code.Shared.catalog_backed module
- flexicon.code.Shared.gendate_utils module
- flexicon.code.Shared.lcm_constants module
- flexicon.code.Shared.morph_type_utils module
- flexicon.code.Shared.rule_patterns module
- flexicon.code.Shared.smart_collection module
- flexicon.code.Shared.string_utils module
- flexicon.code.Shared.wrapper_base module
- Module contents
- flexicon.code.System package
- Submodules
- flexicon.code.System.AnnotationDefOperations module
AnnotationDefOperationsGetAll()Create()Delete()Find()Exists()GetName()SetName()GetHelpString()SetHelpString()GetAnnotationType()GetInstanceOf()GetUserCanCreate()SetUserCanCreate()GetMultiple()SetMultiple()GetPrompt()SetPrompt()GetCopyCutPasteAllowed()FindByType()GetUserCreatableTypes()GetGuid()GetDateCreated()Duplicate()GetSyncableProperties()CompareTo()
- flexicon.code.System.CheckOperations module
CheckOperationsGetAllCheckTypes()CreateCheckType()DeleteCheckType()FindCheckType()GetName()SetName()GetDescription()SetDescription()RunCheck()GetCheckStatus()GetLastRun()GetCheckResults()GetErrorCount()GetWarningCount()GetEnabledChecks()EnableCheck()DisableCheck()IsEnabled()FindItemsWithIssues()GetIssuesForObject()GetGuid()Duplicate()GetSyncableProperties()CompareTo()
- flexicon.code.System.CustomFieldOperations module
CustomFieldOperationsGetAllFields()CreateField()DeleteField()FindField()GetFieldType()GetFieldName()SetFieldName()GetValue()SetValue()ClearValue()GetListValues()AddListValue()RemoveListValue()GetOwnerClass()IsMultiString()IsListType()IsStringType()ClearField()SetListFieldSingle()SetListFieldMultiple()Duplicate()GetSyncableProperties()CompareTo()
- flexicon.code.System.ProjectSettingsOperations module
ProjectSettingsOperationsGetProjectName()SetProjectName()GetDescription()SetDescription()GetVernacularWSs()GetAnalysisWSs()SetDefaultVernacular()SetDefaultAnalysis()GetInterfaceLanguage()SetInterfaceLanguage()GetDefaultFont()SetDefaultFont()GetDefaultFontSize()SetDefaultFontSize()GetLinkedFilesRootDir()SetLinkedFilesRootDir()GetExtLinkRootDir()SetExtLinkRootDir()GetAnalysisWritingSystems()GetVernacularWritingSystems()GetProjectGuid()GetProjectDescription()GetExternalLink()GetAnalysisWritingSystem()GetVernacularWritingSystem()GetDateCreated()GetDateModified()Duplicate()GetSyncableProperties()CompareTo()
- flexicon.code.System.WritingSystemOperations module
WritingSystemOperationsGetAll()GetVernacular()GetAnalysis()Create()Ensure()Delete()GetFontName()SetFontName()GetFontSize()SetFontSize()GetRightToLeft()SetRightToLeft()SetDefaultVernacular()SetDefaultAnalysis()GetDefaultVernacular()GetDefaultAnalysis()GetDisplayName()GetLanguageTag()Exists()ExistsInStore()GetBestString()Duplicate()GetSyncableProperties()CompareTo()
- flexicon.code.System.context_collection module
- flexicon.code.System.phonological_context module
PhonologicalContextcontext_namedescriptionis_simple_context_segis_simple_context_ncis_simple_contextis_complex_context_segis_complex_context_ncis_complex_contextis_boundary_contextsegmentnatural_classboundary_typeas_simple_context_seg()as_simple_context_nc()as_complex_context_seg()as_complex_context_nc()as_boundary_context()concrete
- Module contents
- flexicon.code.TextsWords package
- Submodules
- flexicon.code.TextsWords.DiscourseOperations module
- flexicon.code.TextsWords.ParagraphOperations module
- flexicon.code.TextsWords.SegmentOperations module
SegmentOperationsGetAll()GetAnalyses()GetGloss()GetBaselineText()SetBaselineText()GetFreeTranslation()SetFreeTranslation()GetLiteralTranslation()SetLiteralTranslation()GetNotes()AppendSentence()Delete()SetAnalysis()ReplaceAnalysis()InsertAnalysis()AppendAnalysis()RemoveAnalysis()SplitSegment()MergeSegments()ReparseParagraph()GetOwningParagraph()Exists()GetBeginOffset()GetEndOffset()IsLabel()SetIsLabel()ValidateSegments()GetSyncableProperties()CompareTo()
- flexicon.code.TextsWords.TextOperations module
TextOperationsCreate()Delete()Duplicate()GetSyncableProperties()ApplySyncableProperties()CompareTo()Exists()GetAll()Find()GetTitle()SetTitle()GetName()SetName()GetGenre()GetGenres()SetGenre()GetContents()GetParagraphs()GetParagraphCount()GetMediaFiles()AddMediaFile()GetAbbreviation()GetIsTranslated()SetIsTranslated()
- flexicon.code.TextsWords.WfiAnalysisOperations module
ApprovalStatusTypesWfiAnalysisOperationsGetAll()Create()GetSyncableProperties()CompareTo()Delete()Duplicate()Exists()GetApprovalStatus()SetApprovalStatus()IsHumanApproved()IsComputerApproved()ApproveAnalysis()RejectAnalysis()GetGlosses()GetGlossCount()AddGloss()GetMorphBundles()GetMorphBundleCount()GetMorphemeBundles()GetCategory()GetCategoryAbbrev()SetCategory()GetAgentEvaluation()GetHumanEvaluation()GetEvaluations()GetOwningWordform()GetGuid()
- flexicon.code.TextsWords.WfiGlossOperations module
- flexicon.code.TextsWords.WfiMorphBundleOperations module
WfiMorphBundleOperationsGetAll()Create()Delete()Duplicate()GetSyncableProperties()CompareTo()Reorder()GetForm()SetForm()GetGloss()SetGloss()GetSense()SetSense()GetMorphType()SetMorphType()GetMorph()SetMorph()GetMSA()SetMSA()GetInflType()SetInflType()GetInflectionClass()SetInflectionClass()GetOwningAnalysis()GetGuid()
- flexicon.code.TextsWords.WordformOperations module
- Module contents
Submodules¶
flexicon.code.BaseOperations module¶
- class flexicon.code.BaseOperations.EnumerableWrapper(enumerable)[source]¶
Bases:
objectWraps 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:
objectDescriptor to automatically wrap IEnumerable/iterator return values.
Wraps methods that return C# IEnumerable collections – or plain Python iterators/generators built on top of them (e.g. via self.project.ObjectsIn(…) or a yield-based method body) – to make them Pythonic with .Count, len(), 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! length = len(items) # Works!
- Behavioral collection contract:
Every
GetAllin flexicon returns a behavioral collection: you can always loop it,len()it, index into it, and re-iterate it. The concrete return type –EnumerableWrapper(this decorator, for large/lazily-materialized results), a plainlist(already a sequence, so wrapping is a no-op), or aSmartCollectionsubtype (adds.filter()/type-breakdown display on top of the same sequence guarantees) – is an implementation detail callers never have to branch on. Seedocs/getall-contract.mdfor the full guarantee and rationale.
- class flexicon.code.BaseOperations.OperationsMethod(func)[source]¶
Bases:
objectDescriptor 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:
objectBase 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 flexicon 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()
flexicon.code.FLExGlobals module¶
flexicon.code.FLExInit module¶
flexicon.code.FLExLCM module¶
- flexicon.code.FLExLCM.OpenProject(projectName, ui=None, progress=None)[source]¶
Open a FieldWorks project.
- projectName:
Either the full path including “.fwdata” suffix, or
The name only, opened from the default project location.
- ui:
Optional ILcmUI implementation. When None (the default, since issue #285) a bare HeadlessLcmUI() is used: it never blocks and never silently discards a conflicting save, instead raising FP_ConflictingSaveError so the condition surfaces to the caller.
Interactive, FLEx-hosted callers that genuinely want the WinForms dialogs should pass ui=FwLcmUI(None, ThreadHelper()) explicitly. FwLcmUI opens modal dialogs and marshals through Control.Invoke, which in a process with no message pump blocks the commit thread and, on a conflicting save, silently discards this session’s unsaved writes. See issues #238 and #285.
- progress:
Optional
IThreadedProgressimplementation. When None (the default, since issue #289) a bareHeadlessThreadedProgress()is used: it runs any progress task on the calling thread and allocates no WinForms handle.Interactive callers that want the historical FieldWorks progress dialog may pass
progress=ProgressDialogWithTask(ThreadHelper())explicitly. That object isIDisposableand is disposed after the open completes so Win32 handles do not leak per call.
flexicon.code.FLExProject module¶
- flexicon.code.FLExProject.AllProjectNames()[source]¶
Returns a list of FieldWorks projects that are in the default location.
- class flexicon.code.FLExProject.FLExProject[source]¶
Bases:
objectThis 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=True, strict_transactions=False, ui=None, progress=None)[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.
- strict_transactions:
Default: False. When
Trueon a write-enabled session, enteringTransaction()(or any_FLExTransactionconstructed with no LCM mark/rollback API) raisesFP_TransactionErrorinstead of proceeding without rollback capability. Use this when partial mid-block writes are unacceptable and you prefer a clean failure over degraded Phase 1 behaviour (issue #210). Ignored whenwriteEnabled=False. Does not change the defaultundoable=Truepath, whereBaseOperations._TransactionCMuses real liblcm units of work.- undoable:
Default since 4.4.0: True. Each write runs inside its own named, nesting-aware LCM unit of work, so an exception escaping an operation rolls that operation’s mutations back, and the operation appears in FLEx’s Ctrl+Z menu under its own label. This is the mode the write path is designed for (decision D3 in specs/write-path-transactions/tasks.md).
Only meaningful when writeEnabled=True; ignored otherwise.
Passing
undoable=Falseopts back into the legacy Phase 1 behaviour: one session-longBeginNonUndoableTask()envelope, in whichTransaction()is a labelling/nesting construct only and nothing rolls back – the atomicity unit becomes the whole session (issue #236). It is retained for callers that depend on the old semantics, and it warns once perOpenProject()call. Do not use it when the project may be open in FLEx or another process (D3).Two consequences of the default worth knowing before you rely on per-operation rollback:
Nested blocks join the outer unit of work rather than opening an independent one, so catching an exception from an inner block while still inside the outer block commits that inner block’s partial writes. See docs/EXCEPTION_HANDLING.md.
AbortSession()is anundoable=Falseprimitive. Under this default it returns False between operations and raisesFP_TransactionErrorinside one (D8) – per-operation rollback covers that ground instead.
- ui:
Optional ILcmUI implementation, passed through to FLExLCM.OpenProject(). Default since issue #285: a bare `HeadlessLcmUI()`. It never blocks and never silently reverts; a conflicting save raises FP_ConflictingSaveError instead of discarding this session’s unsaved changes.
from flexicon import FLExProject project = FLExProject() project.OpenProject(“MyProject”, writeEnabled=True) # ui=None -> HeadlessLcmUI() -> conflicting save raises # FP_ConflictingSaveError
Interactive, FLEx-hosted callers that genuinely want the WinForms dialogs should opt in explicitly:
from SIL.FieldWorks.FdoUi import FwLcmUI from SIL.FieldWorks.Common.FwUtils import ThreadHelper project.OpenProject(“MyProject”, writeEnabled=True,
ui=FwLcmUI(None, ThreadHelper()))
FwLcmUI opens modal dialogs and marshals through Control.Invoke – fine for an interactive FLEx-hosted process, but unsafe in a headless one (issue #238): a conflicting save can block the commit thread on a dialog with no owner, or silently discard this session’s unsaved changes.
- progress:
Optional
IThreadedProgress, passed through toFLExLCM.OpenProject(). Default since issue #289: a bare ``HeadlessThreadedProgress()`` (no WinForms handle). Passprogress=ProgressDialogWithTask(ThreadHelper())to opt back into the historical dialog; it is disposed after open completes.
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”.
- classmethod FromOpenProject(donor) FLExProject[source]¶
Attach a flexicon facade to a project someone else already opened.
donor is whatever the host handed Main(): under real FLExTools a flexlibs
FLExProject(flextoolslib/code/FTModules.py:75), under the FLExTools MCP a flexicon one. Returns an object exposing the full flexicon facade over the donor’s cache.Never opens a project, and never closes one. Reopening a project the host is holding raises
FP_FileLockedError, which is the trap any “just make your own flexicon project” advice walks into.The portable module shape – identical under both hosts:
from flexicon import FLExProject def Main(project, report, modifyAllowed): fx = FLExProject.FromOpenProject(project) lex, variants = fx.LexEntry, fx.Variants
Importing the class is not enough on its own: it does not change the instance
Main()is handed. This classmethod is what makes that import load-bearing.Notes:
Idempotent. A donor that is already a flexicon
FLExProjectis returned unchanged, by identity – it owns its project, and a module written against this seam must stay correct under the MCP.Phase 1 only. The view is always
_undoable = False; the host owns the transaction envelope. UseTransaction();UndoableOperation()is refused.Owns nothing.
CloseProject()on the returned view is a no-op andSaveChanges()is refused. The host saves.
- Returns:
- A view over the donor’s cache, or the donor itself
when it is already a flexicon FLExProject.
- Return type:
- Raises:
FP_ParameterError – the donor is missing the cache or
writeEnabled. The message names every absent attribute and the donor’s module.
- CloseProject()[source]¶
Save any pending changes and dispose of the LCM object.
Guard added for issue #243 (spec.md C1/C6/C7): the Phase 1
EndNonUndoableTask()mirror call below is guarded two ways so that a raise there can never skipusm.Save(), which would otherwise discard the whole session’s in-memory work with no data written to disk:HasOpenSessionTask()is checked first. If no envelope is open (e.g. a prior mid-sessionSaveChanges()call already collapsed it – spec.md C9), theEndcall is skipped entirely rather than assumingwriteEnabled and not _undoableimplies the envelope is still present. This is an anomaly by construction in Phase 1 (spec.md C14/C18), so it is logged at ERROR (spec.md C23) rather than debug – see the branch below for exactly what is and is not asserted.Even when the check says an envelope IS open, the
Endcall itself is wrapped in try/except so an unexpected raise there (not just the already-prevented depth-0 case) still cannot preventusm.Save()from running.
End-then-Save order is unchanged (C7) – this does not reorder
usm.Save()ahead of theEndcall; P-5 (spec.md section 2) proved that shape trades one guaranteed raise for another with no save occurring either way.Dispose()/del self.projectrun in afinally(spec.md C15) so the live LCM handle is never leaked, including when the ERROR branch below is taken or whenusm.Save()itself raises.Attached-view no-op: on a project attached with
FromOpenProject(), this method does nothing and returnsNone– the host owns the cache, and a defensive close in an otherwise-correct module must not fail (SPEC 3b).
- property CurrentDepth¶
Raw LCM action-handler nesting depth (issue #243, spec.md C2/C4).
A direct, documented
intpassthrough ofself.project.ActionHandlerAccessor.CurrentDepth– the same value three internal call sites already read in a more lenient form (transaction.py, undoable_operation.py, System/CustomFieldOperations.py). Implemented as a property (matching theCacheproperty’s precedent as a discoverable, no-argument, no-side-effect escape hatch onto raw LCM state) rather than a method, since reading the depth has no side effect and nothing to parameterize.Mode-dependence (frozen P-2 table, spec.md section 2): under
undoable=Falsethe session-longBeginNonUndoableTask()envelope holds this at 1 for the whole session (unchanged insideTransaction()blocks); underundoable=Trueit is 0 outside anUndoableOperation()block and 1 inside one (Transaction()never changes it either way).- Returns:
- The real, unmodified depth. For a read-only
(
writeEnabled=False) project this is legitimately0and is returned WITHOUT raising (spec.md C4) – a pure read has no mutating consequence, soFP_ReadOnlyErrorwould be domain-wrong here.
- Return type:
int
- Raises:
FP_ProjectError – If the project is closed or was never opened.
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True, ... undoable=False) >>> project.CurrentDepth 1
- HasOpenSessionTask()[source]¶
Is the session-long
BeginNonUndoableTask()envelope open?Answers exactly that narrow question (issue #243, spec.md C3) – it is NOT a mode-agnostic “is anything open” predicate, because
CurrentDepth == 1means two structurally different things depending on mode:Under
undoable=False(Phase 1),OpenProject()opens one session-long envelope viaBeginNonUndoableTask()thatCloseProject()must mirror-close withEndNonUndoableTask(). Here, depth > 0 means that envelope is open.Under
undoable=True(Phase 2, the 4.4.0 default), no such envelope is ever opened by construction – eachUndoableOperation()/Transaction()manages its own begin/end pair instead. So this method returnsFalseunconditionally in that mode – a correct fact about that mode, not “nothing to report” – WITHOUT using depth to decide it (depth is still read first, below, purely so a closed/never-opened project raises consistently regardless of mode).
- Returns:
Falsewhenself._undoableisTrue.Otherwise
self.CurrentDepth > 0, read via the same private helperCurrentDepthuses.
- Return type:
bool
- Raises:
FP_ProjectError – If the project is closed or was never opened, in either mode.
Example
>>> project.OpenProject("MyProject", writeEnabled=True, ... undoable=False) >>> project.HasOpenSessionTask() True
- 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:
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 flexicon.
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:
FP_NullParameterError – if interface_type is None.
FP_ParameterError – if neither resolution path produces an instance.
Example
>>> from SIL.LCModel import IMoInflAffMsaFactory >>> factory = project.GetFactory(IMoInflAffMsaFactory) >>> msa = factory.Create()
- Transaction(label='transaction')[source]¶
Return a context manager for labelling and nesting a group of writes.
Mode-dependent semantics (read this before relying on it for safety):
undoable=False(the legacy opt-out mode; the default isundoable=Truesince 4.4.0): there is no rollback. liblcm exposes no reachable “roll back to a mark” primitive in this mode (issue #236; confirmed by reflection over SIL.LCModel.dll – see specs/write-path-transactions/spec.md section 2 and D1 for the specific API name checked and confirmed absent).Transaction()still opens and closes cleanly, and nestedwithblocks (including the per-methodBaseOperations._TransactionCMblocks used internally by Operations methods) still compose without error, but no exception raised inside the block undoes anything. The atomicity unit in this mode is the whole session: a mid-operation exception leaves every mutation applied up to that point sitting in the in-memory cache, and it will be written to disk on the nextSaveChanges()/CloseProject(). A per-session warning to this effect is logged once perOpenProject()call (not once per process or per instance – a secondOpenProject()call in the same session re-logs it), rather than on everyTransaction()call. See docs/EXCEPTION_HANDLING.md.undoable=True: this method itself is unchanged by the B1 rewrite – callingproject.Transaction(label)directly still always returns the Phase 1, no-rollback_FLExTransactionabove (seetest_transaction_body_always_passes_none_none, which locks this). What changed under B1 is the internalBaseOperations._TransactionCM()wrapper that most Operations methods use: it no longer calls this method at all inundoable=Truemode, and instead delegates to_NestingAwareTransaction, which is genuinely transactional – backed directly by liblcm’sUndoableUnitOfWorkHelper, an exception rolls back everything written inside the block. SeeUndoableOperation()for the equivalent public, directly callable entry point in this mode.
The name is kept (see D4 in specs/write-path-transactions/tasks.md): an earlier draft of this spec preferred renaming this method to avoid over-promising, but once the
undoable=Truerewrite lands the name is accurate for the mode this project is migrating towards, so renaming it away would make the name wrong exactly where it will soon be right.- 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) with project.Transaction("import batch"): for word, gloss in data: entry = project.LexEntry.Create(word, "stem") project.Senses.Create(entry, gloss, "en") project.CloseProject()
See also
UndoableOperation() - the
undoable=Truepath; 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.
Depth guard (issue #243, spec.md C20/C21): refuses to call
usm.Save()wheneverCurrentDepth > 0– i.e. while a unit of work is open, in EITHER mode. Live probes (P-5/P-7/P-10-C) measured that callingusm.Save()at depth > 0 raisesInvalidOperationException: Commit at wrong place.from liblcm, and that underundoable=Falsethat failure’s own path collapses the session-long envelope as a side effect, discarding the whole session’s pending work with nothing written to disk (0/25 survivors measured pre-guard). This guard turns that into an honest, fail-fastFP_TransactionErrorbeforeusm.Save()is ever attempted, so the refusal itself discards nothing.Note
Only valid for write-enabled, owned projects. Does NOT call EndNonUndoableTask() - the session stays open. Under
undoable=False, the session-long envelope opened byOpenProject()holdsCurrentDepthat 1 for the entire session, so this method ALWAYS raises if called mid-session in that mode – see the Example below. UseCloseProject()instead, which ends that envelope before saving. Underundoable=True, call this AFTER anUndoableOperation()/Transaction()block has exited (CurrentDepthback to 0), never from inside one.That
CloseProject()advice applies to OWNED projects only – ones this instance opened viaOpenProject(). On a view obtained fromFromOpenProject()it is actively wrong:CloseProject()is a no-op there, so following it would produce a run that reports success and saves nothing.On an attached view the host (FLExTools, or FieldWorks itself) opened the cache and saves it on its own schedule. Make the changes inside
Transaction()and simply return fromMain(); there is nothing for the module to save or close.- Raises:
FP_RuntimeError – If this is a view obtained from
FromOpenProject(). Raised before the write-enabled and depth checks below, so the caller hears that the host owns the save rather than a read-only or transaction-depth diagnosis that would misdescribe the situation.FP_ReadOnlyError – If project is not write-enabled.
FP_TransactionError – If
CurrentDepth > 0– a unit of work is currently open, in either mode.usm.Save()is never attempted when this is raised.
Example (
undoable=True, the 4.4.0 default):with project.UndoableOperation("import batch"): for word in words: project.LexEntry.Create(word, "stem") # SaveChanges() belongs AFTER the block, not inside it -- # CurrentDepth is back to 0 here. project.SaveChanges()
Example (
undoable=False, explicit opt-out):project.OpenProject("MyProject", writeEnabled=True, undoable=False) project.LexEntry.Create("word", "stem") # SaveChanges() here would raise FP_TransactionError: the # session-long envelope opened at OpenProject() holds # CurrentDepth at 1 for the whole session. CloseProject() # ends that envelope first, then saves. project.CloseProject()
- RefreshFromDisk()[source]¶
Reconcile in-memory state with a foreign change and unblock auto-save.
Wraps IUndoStackManager.Refresh(), obtained via the same ObjectRepository(IUndoStackManager) accessor used by SaveChanges() and CloseProject().
Rationale (issue A4, specs/write-path-transactions/spec.md D3): UnitOfWorkService.cs:245 in liblcm refuses to auto-save while m_pendingReconciliation is non-null – LCM’s own comment is “don’t auto-save until the user Refreshes.” In FLEx a human clicks Edit > Refresh. Headless, nothing ever calls the equivalent, so once another client (typically FLEx itself, opened on the same project in shared mode) saves a change that this session must reconcile, saving is wedged for the remainder of the session – in BOTH undoable=True and undoable=False modes, since the guard is in the shared UnitOfWorkService, not in either undo-stack implementation. Calling this method after a detected (or suspected) foreign change clears that pending-reconciliation state so subsequent saves proceed.
- Raises:
FP_ReadOnlyError – If project is not write-enabled.
- Note on the write-enabled guard:
The failure mode this method exists to fix – auto-save permanently refusing to run – is only possible while a write-enabled session holds an open UnitOfWork envelope (BeginNonUndoableTask()/BeginUndoTask()). A read-only session never saves, so there is nothing for a pending reconciliation to block. Guarding here matches SaveChanges(), which raises FP_ReadOnlyError for the same reason: the operation is meaningless outside a write-enabled session.
Example:
project.OpenProject("MyProject", writeEnabled=True, undoable=True) # ... FLEx (or another client) saves a conflicting change ... project.RefreshFromDisk() project.SaveChanges() # No longer wedged
- Note on mode (issue #243, spec.md C21): the Example above requires
undoable=True. Underundoable=Falsethe session-long envelope opened atOpenProject()holdsCurrentDepthat 1 for the whole session, soSaveChanges()always raisesFP_TransactionErrorin that mode – it cannot be called mid-session at all, reconciliation or not.CloseProject()ends that envelope before its ownusm.Save()call, so it reachesusm.Save()at a legal depth; whetherRefreshFromDisk()followed byCloseProject()fully clears a pending-reconciliation wedge underundoable=Falsehas not been measured here and is not claimed.
- SyncForeignChanges()[source]¶
Ingest other LCM peers’ committed changes without closing the session.
Under
undoable=False(the FlexTools / MCP runner mode), the session-longBeginNonUndoableTask()envelope opened atOpenProject()holdsCurrentDepthat 1, which makesSaveChanges()refuse to callusm.Save()(#243). This method temporarily ends that envelope, drivesusm.Save()(which reachesCommit()and foreign-change reconciliation on shared backends), then reopens the envelope in afinallyso callers can keep writing.Unlike
RefreshFromDisk(), which only clears a pending-reconciliation wedge, this wrapper is the supported mid-session save entry point when the non-undoable envelope must stay open for the remainder of the run (issue #292, FlexToolsMCP #96).- Raises:
FP_RuntimeError – On a view from
FromOpenProject()(host owns the envelope).FP_ReadOnlyError – If the project is not write-enabled.
FP_TransactionError – If
undoable=True, ifCurrentDepthis 0 (useSaveChanges()instead), or if depth is not exactly 1 inundoable=Falsemode.FP_ProjectError – If the envelope could not be reopened after a successful
usm.Save().
Example:
project.OpenProject("MyProject", writeEnabled=True, undoable=False) # ... peer A committed; this session must see A's data ... project.SyncForeignChanges() # session envelope is open again; writes continue
- AbortSession()[source]¶
Discard every uncommitted change in the currently open unit of work.
Wraps liblcm’s one real revert primitive,
IActionHandler.Rollback(0)(task A3, specs/write-path-transactions/spec.md section A3). It is coarse – it reverts the whole open unit of work, not a selected subset – but underundoable=Falsethat unit is the entire session, which is exactly the granularity that mode’s atomicity story needs and which was previously unreachable from flexicon.What it does NOT do: it cannot revert anything already written to disk – data that was on disk when the session opened, or anything a prior
CloseProject()committed. “Uncommitted” here means “still only in this process’s cache”.Under
undoable=Falsethat window is unusually wide, and for two reasons worth knowing. The session envelope holds the FSM inProcessingDataChanges, which blocks the auto-save timer outright (UnitOfWorkService.cs:240), so nothing is quietly committed behind your back between operations. For the same reasonSaveChanges()cannot be used to commit mid-session either: it reachesCheckReadyForCommit("Commit at wrong place.")(UnitOfWorkService.cs:304), which requiresReadyForBeginTask. The practical consequence is that in this mode essentially the whole session is abortable, right up toCloseProject().Mode-dependent behavior (read this before relying on it):
undoable=False(the legacy opt-out; you must ask for it explicitly since 4.4.0): this is the intended mode. The session-longBeginNonUndoableTask()opened atOpenProject()is the open unit of work, so this rolls the session back to its state at open (or at the last commit) and then reopens the envelope, so the session stays usable andCloseProject()’s matchingEndNonUndoableTask()still has a task to end. See the O2 catch below for why reopening is not optional.undoable=True: rollback is already automatic and per-operation (UndoableOperation()/_TransactionCMroll back their own block on exception), so there is no session-wide uncommitted state for this method to abort. Between operations nothing is open and this returnsFalse. Inside an open block it raisesFP_TransactionErrorrather than rolling back – see below.
The O2 catch (UndoStack.cs:705-724, recorded in spec.md O2 and reviews/cycle2-explore-liblcm-facts.md F5c):
Rollback(int nDepth)ignoresnDepthentirely – the parameter is documented “[Not used.]” – so it always reverts the whole open unit. There is no partial rollback.It requires
CurrentProcessingState == ProcessingDataChangesand otherwise throwsInvalidOperationException("Rollback not supported in the current state.").CurrentDepthis exactly that state expressed as 1-or-0 (UndoStack.cs:731-734), so theCurrentDepth == 0check below is the precondition test, not a heuristic.On success it leaves the FSM in
ReadyForBeginTask– i.e. it terminates the open task rather than merely emptying it. Inundoable=Falsethat would silently end the session envelope, andCloseProject()would then callEndNonUndoableTask()against a state that has no task to end. This method therefore reopensBeginNonUndoableTask()immediately, making the abort non-terminal in that mode.
Why
undoable=Truerefuses instead of rolling back: in that mode an open unit of work is always owned by anUndoableUnitOfWorkHelper(there is no session envelope). Rolling back underneath it would leave that helper’sDispose()to callRollback/EndUndoTaskagainst a FSM already back inReadyForBeginTask, raising a second exception from thewithblock’s exit and masking whatever the caller was actually handling. Refusing loudly is the honest option; the correct tool inside a block is to let the exception propagate, which rolls that block back by design.Attached views refuse outright. On a project attached with
FromOpenProject()the open unit of work is the HOST’s – a view is unconditionally_undoable = False, so without a guard this method would take theundoable=Falsebranch below andRollback(0)the host’s session-long envelope, discarding unsaved edits the host made before the module was ever called and then replacing that envelope with one this facade opened. Both are the host’s to own (Invariant B), so the call is refused before any action-handler access.- Returns:
- True if a unit of work was open and was rolled back.
False if nothing was open (nothing to abort) – calling
Rollbackin that state would raise, so it is not called.
- Return type:
bool
- Raises:
FP_RuntimeError – If this is a view obtained from
FromOpenProject(). Raised before the write-enabled check, for the same reason as inSaveChanges(): the refusal is about who owns the unit of work, and a read-only diagnosis would imply that a write-enabled host would make the call succeed, which it must not.FP_ReadOnlyError – If the project is not write-enabled.
FP_TransactionError – If
undoable=Trueand a unit of work is open (see above), or if the underlying LCMRollback(0)call fails unexpectedly.FP_ProjectError – If the
undoable=Falseenvelope could not be reopened after a successful rollback. The rollback itself has already taken effect at that point; the session is left without an open task and should be closed.
Example:
# NOTE the explicit undoable=False. Under the 4.4.0 default this # method has nothing session-wide to abort -- see the mode table # above -- and each Create() rolls itself back instead. project.OpenProject("MyProject", writeEnabled=True, undoable=False) try: for word, gloss in messy_input: entry = project.LexEntry.Create(word, "stem") project.Senses.Create(entry, gloss, "en") except Exception: project.AbortSession() # discard the whole partial import raise else: # NOTE: not SaveChanges(). Under undoable=False the # session-long envelope keeps CurrentDepth at 1 for the # whole session (issue #243, spec.md C21), so # SaveChanges() always raises FP_TransactionError here. # CloseProject() ends that envelope first, then saves. project.CloseProject()
See also
- Undo() - reverse one committed
UndoableOperation (
undoable=Trueonly, in-process only).- UndoableOperation() - per-operation rollback, the finer-grained
and preferred mechanism once
undoable=Trueis in use.
- 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:
FP_ReadOnlyError – If project is not write-enabled
FP_TransactionError – If project was not opened with undoable=True
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
Rollback-capable (issue #233, #236-for-undoable): this now delegates to
_FLExUndoableOperation, which constructs liblcm’s ownUndoableUnitOfWorkHelperdirectly (or joins an already-open one, viaActionHandlerAccessor.CurrentDepth) instead of hand-rollingBeginUndoTask/EndUndoTaskcalls. If an exception is raised inside the block and this call was the one that opened the UnitOfWork, the mutations made inside it ARE rolled back –UndoableUnitOfWorkHelper’sRollBackflag defaults to True and is only cleared on a clean exit. If this call instead joined an already-open UnitOfWork (nested inside anotherUndoableOperation()or a_TransactionCMblock), rollback authority belongs to whichever call opened it. See specs/write-path-transactions/spec.md B1.
- 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.
Scope – IN-PROCESS ONLY (issue #235): liblcm’s undo stack (
IActionHandler, obtained here fromLcmCache.ActionHandlerAccessor) lives entirely in this process’s RAM and holds liveICmObjectreferences. Nothing serializes undo records into.fwdata; a freshly openedLcmCachealways starts atUndoableActionCount == 0. There is no cross-process and no cross-session undo: closing and reopening the project – even within the same script – loses the entire stack. Cross-session reversal is a separate, still-open concern tracked at the wrapper layer (flexicon/sync/engine.py’screate_snapshot/Snapshotstubs), not here.- Returns:
- True if undo succeeded, False if there was nothing to undo
(
CanUndo()was False).
- Return type:
bool
- Raises:
FP_TransactionError – If project not opened with undoable=True, or if the underlying LCM
Undo()call fails unexpectedly.
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.
Scope – IN-PROCESS ONLY (issue #235): the same RAM-only limitation documented on
Undo()applies here. liblcm’s redo stack lives entirely in this process’sLcmCache.ActionHandlerAccessor; there is no cross-process or cross-session redo, and a freshly opened project never has anything to redo.- Returns:
- True if redo succeeded, False if there was nothing to redo
(
CanRedo()was False).
- Return type:
bool
- Raises:
FP_TransactionError – If project not opened with undoable=True, or if the underlying LCM
Redo()call fails unexpectedly.
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:
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:
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") >>> # List complex form types without touching lexDB directly >>> for cf_type in project.LexEntry.GetAllComplexFormTypes(): ... print(project.PossibilityLists.GetItemName(cf_type))
- property Texts¶
Access to Text operations.
- Returns:
Instance providing text management methods
- Return type:
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:
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.ApproveAnalysis(analysis) >>> # Get morph bundles >>> bundles = project.WfiAnalyses.GetMorphBundles(analysis)
- property Paragraphs¶
Access to paragraph operations.
- Returns:
Instance providing paragraph management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> text = list(project.Texts.GetAll())[0] >>> para = list(text.ContentsOA.ParagraphsOS)[0] >>> # Get text content >>> text_content = project.Paragraphs.GetText(para) >>> # Set text content >>> project.Paragraphs.SetText(para, "In the beginning...") >>> # Get segments >>> segments = project.Paragraphs.GetSegments(para) >>> print(f"{len(segments)} segments")
- property Segments¶
Access to segment operations.
- Returns:
Instance providing segment management methods
- Return type:
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:
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:
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:
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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Get all allomorphs for an entry >>> entry = project.LexiconGetEntry(0) >>> 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:
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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Get all inflection classes >>> for ic in project.InflectionFeatures.InflectionClassGetAll(): ... name = project.InflectionFeatures.InflectionClassGetName(ic) ... print(f"Inflection class: {name}") >>> # Get all features >>> for feat in project.InflectionFeatures.FeatureGetAll(): ... name = feat.Name.BestAnalysisAlternative.Text ... 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 onproject.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¶
Deprecated discoverability alias for POS.
- Returns:
A distinct, lazily-cached deprecated subclass of
POSOperations. It addresses the same list asproject.POS–IPartOfSpeechinLangProject.PartsOfSpeechOA– and inherits its behaviour, but it is not the same object:project.GramCat is project.POSis False.- Return type:
At list level, a “grammatical category” is a part of speech. The full CRUD surface –
GetAll,Find,Create,AddSubcategory,GetSubcategories,GetParent,Delete– lives onproject.POS. This alias is retained only so callers thinking in FLEx UI terminology (Grammar > Categories) can find the wrapper from either spelling; new code should spell itproject.POS.Two things are deliberately not inherited transparently:
Constructing the alias emits a
DeprecationWarning. The instance is cached, so the warning fires once per project, not once per attribute access.project.GramCat.Create(...)always raisesFP_ParameterError, before any write. The oldCreate(name, parent=None)signature is kept precisely so that a legacy caller gets that explanatory error – namingproject.POS.Create(name, abbreviation)for a top-level category andproject.POS.AddSubcategory(parent, name, abbreviation)for a subcategory – instead of a bareTypeErrorabout a missingabbreviationargument. That raising override is the migration signpost, which is why this property returns aGramCatOperationsrather thanself.POS(issue #276; seespecs/276-gramcat-collection/spec.mdsection 4).
Removal is scheduled for the v5.0.0 boundary, alongside the other deprecated compatibility surfaces.
Three FLEx concepts wear confusingly similar names. They are different LCM classes, and only the first is a category (issue #276):
project.GramCat/project.POS– the category inventory (FLEx: Grammar > Categories). Create, browse, nest and delete categories here.project.Senses.GetGrammaticalInfo(sense)– the sense’s MSA (ILexSense.MorphoSyntaxAnalysisRA), which is what FLEx labels “Grammatical Info.” That is a composite, not a kind of category: useproject.Senses.GetPartOfSpeechObject(sense)for just the category behind it, andproject.MSA.*to build one.project.InflectionFeatures– the feature side of that composite, including the feature-structure types inMsFeatureSystemOA.TypesOCviaTypeFind/TypeCreate. AnIFsFeatStrucTypeis a structural template for feature structures; it is never a grammatical category.
Example
>>> # Reads behave identically -- both address >>> # LangProject.PartsOfSpeechOA: >>> project.GramCat.Find("Verb") >>> project.POS.Find("Verb") >>> >>> # Browse the category inventory: >>> for pos in project.POS.GetAll(): ... print(project.POS.GetName(pos)) >>> >>> # Writes must go through project.POS. Creating a category >>> # needs an abbreviation (it is what interlinear renders); >>> # nest with AddSubcategory: >>> verb = project.POS.Create("Verb", "v") >>> project.POS.AddSubcategory(verb, "Transitive Verb", "vt") >>> >>> # The deprecated spelling refuses, with a pointer: >>> # project.GramCat.Create("Transitive") >>> # -> FP_ParameterError: GramCat.Create() has been >>> # removed (issue #276) ... use >>> # project.POS.Create(name, abbreviation)
- property PhonRules¶
Access to phonological rule operations.
- Returns:
Instance providing phonological rule management methods
- Return type:
Example
>>> from flexicon 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:
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.StrataOSand referenced byIMoInflAffixTemplate.StratumRA,IMoDerivAffMsa.StratumRA,IMoStemMsa.StratumRA,IMoCompoundRule.StratumRA, andIPhPhonologicalRule.StratumRA.- Returns:
Instance providing stratum management methods.
- Return type:
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:
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 flexicon.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:
Example
>>> entry = list(project.LexiconAllEntries())[0] >>> sense = entry.SensesOS[0] >>> verb_pos = project.POS.Find("Verb") >>> # Stem MSA with POS = Verb >>> project.MSA.CreateStem(sense, verb_pos) >>> # Derivational affix that turns nouns into verbs >>> n_pos = project.POS.Find("Noun") >>> v_pos = project.POS.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:
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:
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:
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:
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:
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:
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:
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:
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:
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-wideImportForAllAnalysisWritingSystems().- Return type:
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:
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:
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:
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 the analysis as human-approved (glosses have no >>> # approval concept of their own -- it lives on the analysis) >>> project.WfiAnalyses.ApproveAnalysis(analysis) >>> # 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:
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]) >>> # Morph type lives on the allomorph, not the bundle -- >>> # WfiMorphBundles.SetMorphType is a retired stub that always >>> # raises. Link the bundle to the entry's already-typed >>> # allomorph instead. >>> stem_allomorphs = list(project.Allomorphs.GetAll(stem_entry)) if stem_entry else [] >>> if stem_allomorphs: ... project.WfiMorphBundles.SetMorph(stem, stem_allomorphs[0])
- property Media¶
Access to media file operations.
- Returns:
Instance providing media file management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Get all media files >>> for media in project.Media.GetAll(): ... path = project.Media.GetInternalPath(media) ... mtype = project.Media.GetMediaType(media) ... print(f"{path} ({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:
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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Create a filter for verbs ("LexEntry" is FilterTypes.LEXENTRY) >>> filter_obj = project.Filters.Create( ... "Verbs", "LexEntry", {"pos": "verb"} ... ) >>> # Apply the filter to a collection of entries >>> entries = list(project.LexEntry.GetAll()) >>> results = project.Filters.ApplyFilter(filter_obj, entries) >>> print(f"Found {len(results)} verbs") >>> # Export filter to a file >>> project.Filters.ExportFilter(filter_obj, "/path/to/verbs.json")
- property Discourse¶
Access to discourse chart operations.
- Returns:
Instance providing discourse chart management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Get a text >>> text = list(project.Texts.GetAll())[0] >>> # Create a discourse chart >>> chart = project.Discourse.CreateChart(text, "Constituent Chart") >>> # Add rows >>> row1 = project.Discourse.AddRow(chart) >>> # Get all charts >>> for c in project.Discourse.GetAllCharts(text): ... 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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Create a person >>> consultant = project.Person.Create("Maria Garcia", "en") >>> # Set properties (Gender is an int code; ICmPerson has no >>> # email/phone fields, issue #352) >>> project.Person.SetGender(consultant, 1) >>> 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) ... print(name)
- property Location¶
Access to location operations for managing geographic places.
- Returns:
Instance providing location management methods
- Return type:
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:
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:
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:
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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Create human agent >>> person = project.Person.Create("John Smith", "en") >>> agent = project.Agents.Create("John Smith") >>> project.Agents.SetHuman(agent, person) >>> # Create parser agent (an agent is a "parser" simply by not >>> # calling SetHuman on it) >>> parser = project.Agents.Create("MyParser") >>> project.Agents.SetVersion(parser, "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:
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:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Get a chart >>> text = list(project.Texts.GetAll())[0] >>> chart = project.Discourse.CreateChart(text, "Chart") >>> poss_list = project.PossibilityLists.FindList("Confidence Levels") >>> overlay = project.Overlays.Create("Temporal", poss_list) >>> name = project.Overlays.GetName(overlay) >>> print(f"Overlay: {name}")
- property TranslationTypes¶
Access to translation type operations.
- Returns:
Instance providing translation type methods
- Return type:
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", "en") >>> project.TranslationTypes.SetAbbreviation(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:
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:
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 ScrDrafts¶
Access to Scripture draft operations for saved draft versions.
- Returns:
Instance providing draft management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> # Create a saved version >>> draft = project.ScrDrafts.Create("First Draft - January 2025") >>> print(project.ScrDrafts.GetDescription(draft)) First Draft - January 2025
Notes
Requires a project with Scripture (TranslatedScriptureOA); GetAll() yields nothing otherwise
- property ScrBooks¶
Access to Scripture book operations.
- Returns:
Instance providing book management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> matthew = project.ScrBooks.Find(40) >>> print(project.ScrBooks.GetTitle(matthew)) Matthew
Notes
Requires a project with Scripture (TranslatedScriptureOA); GetAll() yields nothing otherwise
- property ScrNotes¶
Access to Scripture note operations.
- Returns:
Instance providing Scripture note methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> book = project.ScrBooks.Find(40) >>> note = project.ScrNotes.Find(book, 0) >>> print(project.ScrNotes.GetText(note))
Notes
Requires a project with Scripture (TranslatedScriptureOA)
- property ScrSections¶
Access to Scripture section operations.
- Returns:
Instance providing section management methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> book = project.ScrBooks.Find(1) >>> if book: ... section = project.ScrSections.Create(book, "Creation")
Notes
Requires a project with Scripture (TranslatedScriptureOA)
- property ScrTxtParas¶
Access to Scripture text paragraph operations.
- Returns:
Instance providing paragraph methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> book = project.ScrBooks.Find(1) >>> section = project.ScrSections.Find(book, 0) >>> para = project.ScrTxtParas.Find(section, 0) >>> print(project.ScrTxtParas.GetText(para))
Notes
Requires a project with Scripture (TranslatedScriptureOA)
- property ScrAnnotations¶
Access to Scripture annotation operations.
- Returns:
Instance providing annotation methods
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=True) >>> book = project.ScrBooks.Find(40) >>> if book: ... notes = project.ScrAnnotations.GetNotes(book)
Notes
Requires a project with Scripture (TranslatedScriptureOA)
- property DataNotebook¶
Access to data notebook operations for research notes and observations.
- Returns:
Instance providing notebook record management methods
- Return type:
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:
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:
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:
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:
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 viaTagRA. Use this surface to annotate cells; useConstChartMarkersto 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:
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 Parser¶
Access to READ-ONLY morphological parser operations.
Singular, like the other service facades (
POS,LexEntry,MSA): a plural accessor names a collection namespace, and a parser is a service rather than a collection.THE IMPORT BELOW IS FUNCTION-LOCAL ON PURPOSE, and that is FR-003 rather than a style choice. Nothing about the parser is loaded when
flexiconis imported, so a machine whose parser component is missing, relocated, or from a different FieldWorks installation still imports the package – it degrades to “parser unavailable”, carrying a reason, instead of failing at import. Loading is triggered by USE.Nothing this area ADDS writes: none of its six operations records or files a parse result back into the project, and a standing test enforces that by set equality over the public surface rather than by reviewing method names. The limit of the claim, stated so a caller is not misled by it: the generic reordering helpers inherited by every Operations class are still present here, and Swap / MoveBefore / MoveAfter / ApplySyncableProperties take their targets as arguments and will write if handed writable objects. None can record a parse result. See ParserOperations’ class docstring.
- Returns:
Instance providing read-only parser methods.
- Return type:
Example
>>> project = FLExProject() >>> project.OpenProject("MyProject", writeEnabled=False) >>> # Ask first -- asking never raises, on any machine >>> status = project.Parser.GetAvailability() >>> if not status.available: ... print(status.reason) ... else: ... result = project.Parser.ParseWord("mengambil") ... doc = project.Parser.ParseWordXml("mengambil") ... trace = project.Parser.TraceWordXml("mengambil") >>> # Grammar currency is asked, never assumed >>> if status.available and not project.Parser.IsUpToDate(): ... project.Parser.Reload()
- ImportLocalizedLists(language_code, progress=None)[source]¶
Deprecated. Use
project.LocalizedLists.Import(language_code).
- ImportLocalizedListsForEnabledWS(progress=None)[source]¶
Deprecated. Use
project.LocalizedLists.ImportForAllAnalysisWritingSystems().
- 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).
- GetMultiStringDict(multiStringObj)[source]¶
Return a multilingual string field as
{ws_id: text}.- Parameters:
multiStringObj – IMultiString/IMultiUnicode-like object supporting
get_String(ws_handle), orNone.- Returns:
Writing-system Id to normalized text, excluding empty values.
- Return type:
dict
- 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)
For the int handle used by multistring APIs, use
DefaultVernacularWsorGetDefaultVernacularWSHandle().Note: This method now delegates to WritingSystemOperations for single source of truth.
- GetDefaultAnalysisWS()[source]¶
Returns the default analysis writing system: (Language-tag, Name)
For the int handle used by multistring APIs, use
DefaultAnalysisWsorGetDefaultAnalysisWSHandle().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)
- property DefaultVernacularWs¶
Default vernacular writing system handle (int).
Alias for
GetDefaultVernacularWSHandle(). Satisfiescore.types.FlexProjectand matches scripts that expect a property rather than a method call.- Returns:
Handle suitable for
TsStringUtils.MakeString(text, ws).- Return type:
int
- property DefaultAnalysisWs¶
Default analysis writing system handle (int).
Alias for
GetDefaultAnalysisWSHandle(). Satisfiescore.types.FlexProjectand matches scripts that expect a property rather than a method call.- Returns:
Handle suitable for
TsStringUtils.MakeString(text, ws).- Return type:
int
- 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 LinkedFilesMediaOperations.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 fieldSetAudioPath()- 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 typeSetAudioPath()- 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 typeGetAudioPath()- Get audio file path
- 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 ofrecursive=Truematches every otherGetAllaccessor 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.
This is an identity-resolution lookup, not a search: hvoOrGuid is expected to name an object that exists. A well-formed but stale or nonexistent Hvo/Guid is therefore a caller error, not a “not found” result – it never returns None. Callers must catch FP_ParameterError rather than checking the return value for None.
- Raises:
FP_ParameterError – If hvoOrGuid is not an Hvo (int), System.Guid, or str; if a str is not a well-formed guid; or if a well-formed Hvo/Guid does not resolve to an existing object in the project (e.g. a stale reference).
- 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 live
PossibilitiesOSowning sequence for the given list field (elements areICmPossibility/ base LCM interfaces, not pre-cast concrete types).Raises an exception if the field is not a list (single/Atomic or multiple/Collection).
This return value is load-bearing for writes: callers index the sequence and assign into reference fields (e.g.
sense.StatusRA = status_poss[3]). Do not wrap or copy into a Python list inside flexicon.For concrete types (e.g.
LexEntryType), apply the publiccast_to_concrete(#271) to individual elements after read.Note: this returns the top-level
CmPossibilityobjects. Subitems can be found via theSubPossibilitiesOSattribute. 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
CmPossibilityListfor the given field.Returns the
ICmPossibilityfromFindPossibilityByName, orNoneif it can’t be found. The helper does not cast to a concrete ClassName; usecast_to_concrete(#271) when you need one.
- 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.
- Raises:
FP_ParameterError – If entry_ref does not resolve to an object with a ComplexEntryTypesRS field (i.e. is not a LexEntryRef). A base-typed (e.g. ICmObject, HVO-resolved) entry_ref is cast to its concrete type first; see BaseOperations.py:1568-1576 for why the uncast hasattr check is otherwise always False regardless of the concrete object.
- 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.
- Raises:
FP_ParameterError – If entry_ref does not resolve to an object with a ComplexEntryTypesRS field (i.e. is not a LexEntryRef). pythonnet only surfaces the static type’s attributes, so a base-typed (e.g. ICmObject, HVO-resolved) entry_ref must be cast to its concrete type before the check is meaningful – see BaseOperations.py:1568-1576.
- 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.
- property Agent¶
Deprecated alias for
Agents. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Allomorph¶
Deprecated alias for
Allomorphs. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property AnnotationDef¶
Deprecated alias for
AnnotationDefs. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Check¶
Deprecated alias for
Checks. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChart¶
Deprecated alias for
ConstCharts. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChartCellTag¶
Deprecated alias for
ConstChartCellTags. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChartClauseMarker¶
Deprecated alias for
ConstChartClauseMarkers. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChartMarker¶
Deprecated alias for
ConstChartMarkers. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChartRow¶
Deprecated alias for
ConstChartRows. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ConstChartWordGroup¶
Deprecated alias for
ConstChartWordGroups. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property CustomField¶
Deprecated alias for
CustomFields. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Environment¶
Deprecated alias for
Environments. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Etymologies¶
Deprecated alias for
Etymology. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Example¶
Deprecated alias for
Examples. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Filter¶
Deprecated alias for
Filters. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property GramCats¶
Deprecated alias for
GramCat. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property InflectionFeature¶
Deprecated alias for
InflectionFeatures. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property LexEntries¶
Deprecated alias for
LexEntry. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property LexReference¶
Deprecated alias for
LexReferences. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property LocalizedList¶
Deprecated alias for
LocalizedLists. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property MSAs¶
Deprecated alias for
MSA. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property MorphRule¶
Deprecated alias for
MorphRules. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property NaturalClass¶
Deprecated alias for
NaturalClasses. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Note¶
Deprecated alias for
Notes. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Overlay¶
Deprecated alias for
Overlays. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Paragraph¶
Deprecated alias for
Paragraphs. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Parsers¶
Deprecated alias for
Parser. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property PhonFeature¶
Deprecated alias for
PhonFeatures. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property PhonRule¶
Deprecated alias for
PhonRules. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Phoneme¶
Deprecated alias for
Phonemes. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property PossibilityList¶
Deprecated alias for
PossibilityLists. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Pronunciation¶
Deprecated alias for
Pronunciations. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Publication¶
Deprecated alias for
Publications. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ReversalEntry¶
Deprecated alias for
ReversalEntries. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property ReversalIndex¶
Deprecated alias for
ReversalIndexes. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Segment¶
Deprecated alias for
Segments. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property SemanticDomain¶
Deprecated alias for
SemanticDomains. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Sense¶
Deprecated alias for
Senses. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Stratum¶
Deprecated alias for
Strata. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Text¶
Deprecated alias for
Texts. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property TranslationType¶
Deprecated alias for
TranslationTypes. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Variant¶
Deprecated alias for
Variants. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property WfiAnalysis¶
Deprecated alias for
WfiAnalyses. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property WfiGloss¶
Deprecated alias for
WfiGlosses. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property WfiMorphBundle¶
Deprecated alias for
WfiMorphBundles. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property Wordform¶
Deprecated alias for
Wordforms. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
- property WritingSystem¶
Deprecated alias for
WritingSystems. Emits a DeprecationWarning and forwards to the canonical accessor (issue #200).
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 flexicon.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 flexicon.code.PythonicWrapper import p
for sense in p(entry).Senses:
print(p(sense).Gloss)
- class flexicon.code.PythonicWrapper.PythonicWrapper(obj)[source]¶
Bases:
objectWrapper 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:
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:
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:
ExceptionException 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:
ExceptionException 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
- exception flexicon.code.exceptions.FP_DeduplicationError(item_kind, entry_hvo, found, removed, cause=None)[source]¶
Bases:
FP_RuntimeErrorRaised when duplicate items were detected but could not all be removed.
- exception flexicon.code.exceptions.FP_ConflictingSaveError(message)[source]¶
Bases:
FP_RuntimeErrorRaised when LCM reports that another client saved changes which cannot be reconciled with this session’s unsaved changes.
Raised by
flexicon.code.headless_ui.HeadlessLcmUI.ConflictingSave(). Raising is deliberate: the alternatives LCM offers are to block on a modal dialog or to discard the caller’s unsaved work; neither is acceptable unattended. The caller is expected to abandon or retry the operation.Subclasses
FP_RuntimeError(rather thanFP_ProjectError) because the condition is discovered mid-session, on a save that occurs after the project is already open and in use – it is a runtime failure of an in-progress write, not a problem opening the project.
flexicon.code.headless_ui module¶
A non-blocking ILcmUI for processes with no WinForms message pump.
LCM asks its ILcmUI for decisions at several points, most importantly on a
conflicting save. The default implementation used by FieldWorks, and formerly
used unconditionally by flexicon (until issue #285 flipped the default to
HeadlessLcmUI), is FwLcmUI, a WinForms adapter whose members open
modal dialogs and marshal through Control.Invoke. In a process with no
message pump that produces three distinct failures (issue #238):
ConflictingSave()opensConflictingSaveDlg, which has no close box (ControlBox = false), on the desktop with no owning application. Worse, its polarity is dangerous: anything other thanOKreturnstrue, andUnitOfWorkService.GetUserInputOnConflictingSaveresponds totrueby callingRevertToSavedState()– discarding the caller’s unsaved work.DisplayMessagemarshals throughISynchronizeInvoke. It is reached fromXMLBackendProvider.ReportProblemon the background commit thread, so a failed write hangs that thread, andCompleteAllCommits()then hangs the main thread on cache dispose.FwLcmUIis constructed withhelpTopicProvider = None, andDisplayMessagedereferencesm_helpTopicProvider.HelpFilefor any non-empty help topic.
SIL.LCModel.SilentLcmUI is not a safe substitute: its ConflictingSave()
returns true unconditionally, i.e. silent total discard of unsaved changes
with no message and no exception. That is strictly worse than the dialog.
HeadlessLcmUI never blocks, never marshals, and never silently discards.
Every decision point takes the non-destructive branch and logs; a conflicting
save raises FP_ConflictingSaveError so the condition surfaces to the caller
as an exception it can handle.
Usage:
from flexicon import FLExProject
from flexicon import HeadlessLcmUI # also importable from
# flexicon.code.headless_ui
project = FLExProject()
project.OpenProject("MyProject", writeEnabled=True) # ui=None -> HeadlessLcmUI()
Since issue #285, passing no ui already gets you a bare HeadlessLcmUI()
– that is now the library-wide default. Pass ui=FwLcmUI(None,
ThreadHelper()) explicitly to opt back into the historical, WinForms-dialog
behaviour.
- class flexicon.code.headless_ui.HeadlessLcmUI(raise_on_conflicting_save=True)[source]¶
Bases:
ObjectILcmUIthat makes non-destructive decisions without blocking.Implements all ten methods and both properties of
SIL.LCModel.ILcmUI.- property SynchronizeInvoke¶
SingleThreadedSynchronizeInvoke– runs LCM notification callbacks inline on the calling thread.FwLcmUImarshals through a real UI pump and can deadlock headless processes (#238). ReturningNoneavoided that but breaks every write once anIVwNotifyChangesubscriber exists (HermitCrab parser, issue #441): liblcm dereferencesSynchronizeInvokeunguarded inUnitOfWorkService.SendPropChangedNotificationsandUndoStack.DoTasksForEndOfPropChanged.SingleThreadedSynchronizeInvoke.InvokeRequiredisFalse, soSynchronizeInvokeExtensions.Invokeexecutes the action immediately without cross-thread dispatch.HeadlessLcmUI.DisplayMessagestill logs directly and does not use this property.
- property LastActivityTime¶
- TouchActivity()[source]¶
Record caller activity.
UnitOfWorkService.SaveOnIdleconsultsLastActivityTimeto decide whether to defer an auto-save, so a long-running caller should touch this periodically.
- ConflictingSave()[source]¶
Report whether to revert this session’s changes to the saved state.
Returns False – never revert – and by default raises so the caller learns that a reconcile failed. LCM calls this only after
ChangeReconciler.OkToReconcileChanges()has already determined the foreign changes cannot be merged, so by this point some manual resolution is required either way.
- ReportException(error, isLethal)[source]¶
Returns False: do not attempt to continue after a lethal error.
- Retry(msg, caption)[source]¶
Returns False. Retrying unattended risks an unbounded loop on a persistent condition such as a locked file.
- OfferToRestore(projectPath, backupPath)[source]¶
Returns False. Restoring from a backup unattended would overwrite the project; that decision belongs to a human.
flexicon.code.lcm_casting module¶
LCM Object Casting Utilities for pythonnet.
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 flexicon.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
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
Entry-ref type: LexEntryRef (ILexEntry.EntryRefsOS elements; needed to reach ComplexEntryTypesRS / ComponentLexemesRS / PrimaryLexemesRS / VariantEntryTypesRS on a base-typed or HVO-resolved entry_ref)
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.
Public API. Import it as:
from flexicon import cast_to_concrete
This is the supported remedy for the whole
'ICmObject' object has no attribute 'X'failure class. pythonnet respects .NET interface typing strictly, so an element pulled out of a collection typed asIEnumerable<ICmObject>(or any base interface) exposes only the base interface’s members, even when the underlying object is aLexEntrywith aHeadWord.cast_to_concretelooks upobj.ClassNameand hands back a view typed as the concrete interface, from which the derived members are reachable.flexicon’s own Operations classes cast internally, so most callers never need this. It is exported as the escape hatch for two cases that stay outside that coverage:
Direct-LCM work – when you have reached past the wrapper API and are holding raw LCM objects yourself.
Collections that are legitimately polymorphic, such as
ILexEntry.ComponentLexemesRSorILexReference.TargetsRS, whose elements may each be either anILexEntryor anILexSense.
- Totality guarantee
This function is total: it never raises for an input it does not recognise. An object whose
ClassNameis not in the mapping, an object with noClassNameat all, and a cast that fails inside the CLR all yield the original object, unchanged. That is precisely why it is preferable to the hand-rolledILexEntry(x)workaround, which throws whenxis legitimately anILexSense– exactly the case a polymorphic collection guarantees you will hit. Because the result may be the uncast original, guard derived-member access withhasattr(orgetattr(..., None)) rather than assuming the cast landed.The corollary is that
cast_to_concreteis not a validator: a return value is never evidence that the object was of any particular type. Checkobj.ClassNameif you need to know.
- Parameters:
obj – An LCM object with a ClassName property (e.g., IMoMorphSynAnalysis, IMoForm, or any ICmObject). Any other object is returned as-is.
- Returns:
The object cast to its concrete interface type, or the original object if the ClassName is not recognized or casting fails.
Example:
from flexicon import cast_to_concrete # A polymorphic collection: elements may be entries OR senses. for component in entry.EntryRefsOS[0].ComponentLexemesRS: concrete = cast_to_concrete(component) headword = getattr(concrete, "HeadWord", None) # entries only if headword is not None: print(headword.Text) # 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 it has no ClassName attribute at all
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, which is also the first point at which SIL.LCModel is imported – importing this module (or
flexiconitself) needs no FieldWorks install
- flexicon.code.lcm_casting.cast_all(collection)[source]¶
Materialise collection as a list with every element cast to its concrete LCM interface.
This is the collection-level counterpart to cast_to_concrete(), added for issue #270: the Pattern A sweep cast .Owner return sites but left every collection getter handing back raw base-interface elements, so collection elements could not be round-tripped back into flexicon methods (isinstance(comp, ILexEntry) was False for every element of GetComplexFormComponents(), and hasattr(item, “SubPossibilitiesOS”) was False for elements of a possibility list).
Prefer BaseOperations._GetTypedElements() from inside an Operations class – it delegates here and saves each class importing this module.
- Parameters:
collection – Any iterable of LCM objects (an ILcmOwningSequence, ILcmReferenceSequence, a generator, or a plain list). None is accepted and yields an empty list.
- Returns:
- A new list of the same length and order, each element passed
through cast_to_concrete(). Elements whose ClassName is not registered come back unchanged, so the call is total and safe over heterogeneous or non-LCM contents.
- Return type:
list
Notes
Deliberately NOT applied blanket-wise inside EnumerableWrapper._ensure_list(). See issue #270 for the reasoning: (1) most affected getters return plain Python lists which _needs_enumerable_wrap() intentionally does not wrap, so a wrapper-level cast would miss them; (2) it would add a per-element ClassName lookup to every large GetAll* in the library; and (3) it would silently change element identity for EnumerableWrapper.__contains__/== callers that pass in an uncast object.
- 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.get_inflection_class_from_msa(msa)[source]¶
Get the inflection class (IMoInflClass) from an MSA, if any.
IWfiMorphBundlehas noInflClassRAmember of its own – the inflection class lives on the bundle’s linked MSA (IMoStemMsa.InflectionClassRA), reached viabundle.MsaRA. This is the single navigation path for that lookup: callers should not re-implement “MsaRA -> cast -> narrow to IMoStemMsa -> InflectionClassRA” at each call site (issue #259 / lcm-member-truth-sweep C10).- Parameters:
msa – An MSA object (
IMoMorphSynAnalysisor a derived type), orNone.- Returns:
The inflection class if
msais aMoStemMsawith one set. ReturnsNonefor aNonemsa, for any non-stem MSA subtype (MoDerivAffMsa,MoInflAffMsa,MoUnclassifiedAffixMsa), and for aMoStemMsawith no inflection class set. Never raises.- Return type:
IMoInflClass or None
Example:
from flexicon.code.lcm_casting import get_inflection_class_from_msa infl_class = get_inflection_class_from_msa(bundle.MsaRA) if infl_class: name = infl_class.Name.BestAnalysisAlternative.Text
Notes
Returns None rather than raising exceptions for robustness.
Deliberately does NOT fall back to MoDerivAffMsa.FromInflectionClassRA/ToInflectionClassRA – those are a different pair of properties with different semantics; use cast_to_concrete() directly if you need one of them.
- flexicon.code.lcm_casting.set_inflection_class_on_msa(msa, infl_class)[source]¶
Set the inflection class (IMoInflClass) on an MSA’s InflectionClassRA, if that MSA subtype carries one.
Mirrors
get_inflection_class_from_msa()’s navigation for the write side:msa->cast_to_concrete()-> narrow toIMoStemMsa-> setInflectionClassRA. This is the single navigation path for that write: callers should not re-implement it at each call site (issue #259 / lcm-member-truth-sweep C10/C11).- Parameters:
msa – An MSA object (
IMoMorphSynAnalysisor a derived type), orNone.infl_class – The
IMoInflClassto assign, orNoneto clear it.
- Returns:
True if
msais aMoStemMsaand itsInflectionClassRAwas set toinfl_class. False ifmsaisNoneor itsClassNameis notMoStemMsa– there was no writable target, and nothing was changed.- Return type:
bool
Notes
Never raises for a
Noneor non-stemmsa; returns False instead so callers can build their own diagnostic naming the actual MSA state (seeWfiMorphBundleOperations.SetInflectionClass, which raisesFP_ParameterErrorwith the bundle’s MSAClassName).Deliberately does NOT fall back to
MoDerivAffMsa.FromInflectionClassRA/ToInflectionClassRA– those are a different pair of properties with different semantics; usecast_to_concrete()directly if you need one of them.Because an MSA (
IMoStemMsa) is typically shared – referenced byLexSense.MorphoSyntaxAnalysisRAand by everyWfiMorphBundle.MsaRAthat points at it – writing through this helper changes the value for every bundle and sense that shares the MSA. That fan-out is correct FLEx behaviour (the MSA is the shared “Grammatical Info”), not a bug; see the #259 domain ruling.
- 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 flexicon.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 is not a concrete type in this LCM (issue #326), so any object claiming that ClassName is returned unchanged.
- 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 flexicon.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 flexicon.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 flexicon.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 flexicon.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('StrucDescOS' 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