Skip to main content
Consistent names make the codebase easier to navigate and reduce cognitive load for contributors. Follow these patterns for methods, classes, variables, files, and docstrings.

Method Naming Patterns

Public API Methods

PatternPurposeExample
check_*Public entry points for spell checkingcheck(), check_batch(), check_async()
validate_*Internal validation methodsvalidate(), validate_sentence()
get_*Data retrieval methodsget_syllable_frequency(), get_word_pos()
is_*Boolean validation checksis_valid_syllable(), is_valid_word()
has_*Existence checks (dictionary membership)has_syllable(), has_word()
create_*Factory methodscreate_default(), create_fast()
build_*Builder pattern methodsbuild(), build_from_corpus()

Distinction: is_* vs has_*

  • is_valid_*(): May perform validation beyond existence check (e.g., rule validation)
  • has_*(): Pure existence check - only tests dictionary membership
# is_valid_syllable may check orthographic rules + dictionary
provider.is_valid_syllable("မြန်")  # True if valid Myanmar syllable AND in dictionary

# has_syllable only checks dictionary membership
provider.has_syllable("မြន်")  # True if in dictionary, regardless of orthographic validity

Distinction: check_* vs validate_*

  • check_*(): High-level public API (returns Response objects)
  • validate_*(): Lower-level internal methods (returns List[Error])
# Public API - full spell checking pipeline
result = checker.check("မြန်မာ")  # Returns Response with errors, suggestions, metadata

# Internal - validation only
errors = validator.validate("မြန်မာ")  # Returns List[Error]

Class Naming Patterns

PatternPurposeExample
*ValidatorValidation logicSyllableValidator, WordValidator, ContextValidator
*ProviderData access abstractionDictionaryProvider, SQLiteProvider
*CheckerAnalysis/checking componentsNgramContextChecker, SemanticChecker
*FactoryObject creationComponentFactory, POSTaggerFactory
*ConfigConfiguration classesSpellCheckerConfig, SymSpellConfig
*StrategyStrategy pattern implementationsValidationStrategy, ToneValidationStrategy
*ErrorError typesSyllableError, WordError, ContextError

Variable Naming

General Rules

  1. Use snake_case for variables and functions
  2. Use PascalCase for classes
  3. Use UPPER_SNAKE_CASE for constants
  4. Use descriptive names that indicate purpose

Specific Patterns

ContextPatternExample
Syllable datasyllable_*syllable_frequency, syllable_cache
Word dataword_*word_frequency, word_errors
Configuration*_configsymspell_config, ngram_config
Cache instances*_cachesyllable_cache, bigram_cache
Thresholds*_thresholdbigram_threshold, confidence_threshold
Counts/sizes*_count, *_sizesyllable_count, cache_size
Flagsuse_*, enable_*, is_*use_phonetic, enable_caching, is_valid

Avoid Ambiguous Names

AvoidPreferReason
datasyllable_data, word_frequenciesToo generic
resultvalidation_result, check_responseUnclear what type
tempcached_value, intermediate_scoreNon-descriptive
valvalue, syllable_valueAbbreviated
idxindex, word_indexAbbreviated
cbcallback, on_completeAbbreviated

Private Method Naming

Use single underscore prefix for all private methods:
class SpellChecker:
    def check(self, text):        # Public
        self._validate(text)       # Private
        self._build_response()     # Private

    def _validate(self, text):     # Single underscore - private
        pass

    def _build_response(self):     # Single underscore - private
        pass
Do NOT use double underscore except for Python name mangling requirements:
# Avoid
def __compute_score(self):  # Double underscore - unnecessary

# Prefer
def _compute_score(self):   # Single underscore - standard private

Parameter Naming

Boolean Parameters

Use positive names that indicate the enabled state:
# Good
def check(text, use_context_checker=True, enable_suggestions=True):
    pass

# Avoid
def check(text, disable_context=False, no_suggestions=False):
    pass

Configuration Parameters

Match the configuration class field names:
# Config class
class SymSpellConfig:
    prefix_length: int = 10
    beam_width: int = 50

# Method parameters should match
def create_symspell(prefix_length=10, beam_width=50):
    pass

File Naming

TypePatternExample
Modulesnake_case.pyspell_checker.py, ngram_context.py
Test filetest_*.pytest_spell_checker.py
Config file*_config.py or *_configs.pyalgorithm_configs.py
Interfaceinterfaces.py or base.pyproviders/base.py
Constantsconstants.pytraining/constants.py

Docstring Conventions

Follow Google-style docstrings:
def get_syllable_frequency(self, syllable: str) -> int:
    """
    Get corpus frequency count for a syllable.

    Args:
        syllable: Myanmar syllable (Unicode string) to look up.

    Returns:
        Integer frequency count. Returns 0 if syllable not found.

    Raises:
        ValueError: If syllable is empty string.

    Example:
        >>> provider.get_syllable_frequency("မြန်")
        15432
    """
    pass

Return Type Documentation

For complex return types, document the structure:
def analyze(self, text: str) -> Tuple[List[Error], Dict[str, Any]]:
    """
    Analyze text for spelling errors.

    Returns:
        Tuple containing:
            - errors (List[Error]): List of detected errors
            - metadata (Dict[str, Any]): Analysis metadata with keys:
                - "processing_time" (float): Time in seconds
                - "word_count" (int): Number of words analyzed
                - "error_rate" (float): Errors per word ratio
    """
    pass