Skip to content

Complete type annotations: 100% functions, 56.56% variables, eliminate 25+ Any types - #1272

Merged
bact merged 43 commits into
devfrom
copilot/add-type-hints-to-submodules-one-more-time
Feb 4, 2026
Merged

Complete type annotations: 100% functions, 56.56% variables, eliminate 25+ Any types#1272
bact merged 43 commits into
devfrom
copilot/add-type-hints-to-submodules-one-more-time

Conversation

Copilot AI commented Feb 3, 2026

Copy link
Copy Markdown
Contributor

What do these changes do

Systematically improves type coverage across the codebase:

  • Functions/methods: 100% coverage (725/725)
  • Variables: 56.56% coverage (655/1158), up from 35.10% (+251 annotations)
  • Type precision: Replaced 25+ Any types with library-specific types by investigating external source code

Key improvements:

  • Module variables: 190+ annotations across 40+ files (constants, patterns, configs)
  • Instance variables: 60+ annotations in model classes
  • Precise types: Replaced Any with actual types from transformers, spacy, gensim, numpy, onnxruntime, sentencepiece

Example transformations:

# Before: Generic Any
class WangChanGLM:
    model: Any
    tokenizer: Any

# After: Precise types from transformers library
class WangChanGLM:
    model: PreTrainedModel
    tokenizer: PreTrainedTokenizerBase
# Before: Generic Any in numpy operations
class FastTextEncoder:
    embeddings: Any
    nn_session: Any
    
    def get_word_vector(self) -> Any: ...

# After: Specific numpy and ONNX types
class FastTextEncoder:
    embeddings: NDArray[np.float32]
    nn_session: InferenceSession
    
    def get_word_vector(self) -> NDArray[np.float32]: ...

Files with major improvements:

  • wangchanberta/core.py: CamembertTokenizer, TokenClassificationPipeline
  • coref/_fastcoref.py: Language, CorefModel
  • spell/words_spelling_correction.py: NDArray types, InferenceSession
  • augment/lm/fasttext.py: FastText, KeyedVectors
  • translate/tokenization_small100.py: SentencePieceProcessor

What was wrong

Type annotations were incomplete:

  • Only 35% of variables had type annotations
  • Many attributes used generic Any instead of precise library types
  • Missing type information reduced IDE support and type safety

How this fixes it

Variable annotations: Added 251 annotations to module constants, instance variables, and class attributes across 60+ files using proper types (dict[str, str], Pattern[str], etc.).

Precise types: Investigated external library source code (transformers, spacy, fastcoref, gensim, etc.) to replace Any with actual types. Used TYPE_CHECKING guards to avoid runtime overhead.

Dev branch integration: Merged latest dev changes (ThaiNNER refactoring) while maintaining type improvements.

Your checklist for this pull request

  • Passed code styles and structures
  • Passed code linting checks and unit test
Original prompt

Iterating to incrementally add type hints to submodules to reach 100% type hint coverage.

Strategy

Goals

  • Reach 100% type hints in the entire repo, make the package a typed package, while keeping maintainability.

Instructions

  • Follow best practices and standard Python type hint patterns.
  • Start small in the area with high confidence (like highly tested submodules or functions), then gradually grow one submodule at a time.
  • Use mypy as main assistant.
    • mypy is already in "dev" extra dependencies in pyproject.toml
    • mypy configuration is in pyproject.toml
    • Sometimes mypy may report errors wrongly due to cache issues. Try to reset the cache.
  • Use pyright, pyrefly, and pytype for second opinions.
  • Required dependencies for each test suite are in pyproject.toml. Install them to avoid errors. See https://github.com/PyThaiNLP/pythainlp/blob/dev/tests/README.md
  • Use native type in type hint (list, tuple, .. instead of List, Tuple, ..)
  • Do not use A | B style Union, use full Union[] instead.
  • We want to keep compatibility with Python 3.9 strict and allow type inspection tools to work correctly.
  • When insert typing imports, put it in appropriate location and order
  • Use "if TYPE_CHECKING import" block when possible.
  • When reordering the imports, beware of circular import. Read comments near imports to get more information.
  • Remove unused imports
  • Do not allow the use of assert in production code (it is only allowed for testing and debugging).
  • Try to fix the type, the scope logic, or do the casting, before putting #type: ignore comment.
  • When dealing with types from external libraries:
    • Check if type information is provided (maybe through stubs). If it is, cast wrapper may not necessary.
    • If return type is not provided, may be it is appropriate to use # type: ignore[no-any-return] annotation for clarity.
    • Analyse source code of external libraries to validate correct types
  • Recheck necessity when do casting.
  • Recheck necessity of # noqa: and # type: ignore
  • Provide type stubs as necessary.
  • After changes for type hints, recheck for functionality correctness.
  • Recheck docstring and documentation consistency with the code; They should match the updated type hints.
  • Recheck formatting with ruff
  • Do another code review
  • Address code review feedback

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI assigned Copilot and bact Feb 3, 2026
@bact bact added refactoring a technical improvement which does not add any new features or change existing features. labels Feb 3, 2026
@bact bact modified the milestone: 5.3 Feb 3, 2026
Copilot AI and others added 4 commits February 3, 2026 16:11
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
…dules

Co-authored-by: bact <128572+bact@users.noreply.github.com>
…anslate modules

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title [WIP] Add type hints to submodules for 100% coverage Add type hints incrementally to reach 87.78% coverage Feb 3, 2026
Copilot AI requested a review from bact February 3, 2026 16:25
Copilot AI and others added 7 commits February 3, 2026 16:27
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
…ert, soundex modules

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
@bact
bact marked this pull request as ready for review February 3, 2026 16:43
…m_onnx

Co-authored-by: bact <128572+bact@users.noreply.github.com>
@coveralls

coveralls commented Feb 3, 2026

Copy link
Copy Markdown

Coverage Status

coverage: 65.227% (-0.5%) from 65.703%
when pulling c382092 on copilot/add-type-hints-to-submodules-one-more-time
into 0eaff7f on dev.

Copilot AI and others added 4 commits February 3, 2026 16:49
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
- pythainlp/ulmfit/core.py: merge_wgts
- pythainlp/tokenize/multi_cut.py: serialize, LatticeString.__new__
- pythainlp/ulmfit/tokenizer.py: ThaiTokenizer.add_special_cases
- pythainlp/phayathaibert/core.py: ThaiTextProcessor._replace_rep
- pythainlp/ulmfit/preprocess.py: _replace_rep (2 functions)
- pythainlp/util/normalize.py: _last_char
- pythainlp/wangchanberta/core.py: _get_tokenizer, ThaiNameTagger._clear_tag, ThaiNameTagger._IOB, NamedEntityRecognition._fix_span_error
- pythainlp/coref/_fastcoref.py: FastCoref._to_json
- pythainlp/tokenize/budoux.py: _init_parser
- pythainlp/tokenize/etcc.py: _cut_etcc
- pythainlp/tokenize/nlpo3.py: _ensure_default_dict_loaded
- pythainlp/khavee/core.py: KhaveeVerifier.check_karu_lahu

All functions now have complete parameter and return type hints using Python 3.9+ compatible syntax (Union[], Optional[], not |).

Co-authored-by: bact <128572+bact@users.noreply.github.com>
All 720 functions now have complete type hints. Updated CSV and JSON files reflect zero functions with missing or incomplete type hints.

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI and others added 7 commits February 3, 2026 20:20
Added type annotations to ~50+ more module-level variables:
- All __all__ lists in __init__.py files typed as list[str]
- Translation/transliteration modules
- Tag modules (orchid, blackboard)
- Morpheme, augment, chat, classify, tools modules

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Added type annotations to utility module variables:
- pythainlp/util/morse.py: 4 variables
- pythainlp/util/emojiconv.py: 1 variable
- pythainlp/util/wordtonum.py: 6 variables

All Pattern[str] properly annotated for regex patterns

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
- Added instance variable annotations in __init__ methods for:
  * pythainlp/generate/core.py: Unigram, Bigram, Trigram classes (20 vars)
  * pythainlp/transliterate/w2p.py: Thai_W2P class (20 vars)
  * pythainlp/translate/tokenization_small100.py: SMALL100Tokenizer (14 vars)
  * pythainlp/augment/wordnet.py: WordNetAug class (12 vars)
  * pythainlp/transliterate/thai2rom.py: ThaiTransliterator, Encoder, etc. (12 vars)
  * pythainlp/tag/_tag_perceptron.py: AveragedPerceptron, PerceptronTagger (11 vars)
  * pythainlp/transliterate/thaig2p.py: ThaiG2P, Encoder, Decoder, etc. (11 vars)
  * pythainlp/wangchanberta/core.py: ThaiNameTagger, NamedEntityRecognition (11 vars)
  * pythainlp/generate/wangchanglm.py: WangChanGLM class (10 vars)
  * pythainlp/word_vector/core.py: WordVector class (3 vars)
  * pythainlp/tag/named_entity.py: NER, NNER classes (4 vars)
  * pythainlp/transliterate/thaig2p_v2.py: ThaiG2P class (1 var)
  * pythainlp/transliterate/thai2rom_onnx.py: Seq2Seq_ONNX class (7 vars)
  * pythainlp/summarize/freq.py: FrequencySummarizer class (4 vars)
  * pythainlp/tokenize/multi_cut.py: LatticeString class (3 vars)
  * pythainlp/ulmfit/tokenizer.py: BaseTokenizer, ThaiTokenizer (2 vars)
  * pythainlp/tag/crfchunk.py: CRFchunk class (3 vars)

Total: ~150+ instance variable annotations added

Co-authored-by: bact <128572+bact@users.noreply.github.com>
- Added instance variable annotations in __init__ methods for:
  * pythainlp/augment/lm/fasttext.py: FastTextAug class (3 vars)
  * pythainlp/augment/word2vec/core.py: Word2VecAug class (3 vars)
  * pythainlp/tag/thainer.py: ThaiNameTagger class (2 vars)
  * pythainlp/spell/words_spelling_correction.py: FastTextEncoder class (12 vars)

Total: ~20+ instance variable annotations added in this batch
Cumulative: ~170+ annotations added across all batches

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
…variables

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title 🎉 Complete class attribute type annotations - 100% coverage achieved across entire codebase Complete type annotations: 100% functions, 56.56% variables (+21.46pp) Feb 3, 2026
…e spaCy and fastcoref types

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title Complete type annotations: 100% functions, 56.56% variables (+21.46pp) Complete type annotations: 100% functions, 100% class attributes, 56.56% variables with precise library types Feb 3, 2026
…l and PreTrainedTokenizerBase

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title Complete type annotations: 100% functions, 100% class attributes, 56.56% variables with precise library types Complete type annotations: 100% functions, 56.56% variables, replace Any with precise library types Feb 3, 2026
Copilot AI and others added 2 commits February 4, 2026 07:24
…ules

Co-authored-by: bact <128572+bact@users.noreply.github.com>
…ch 2

Co-authored-by: bact <128572+bact@users.noreply.github.com>
@sonarqubecloud

sonarqubecloud Bot commented Feb 4, 2026

Copy link
Copy Markdown

Copilot AI changed the title Complete type annotations: 100% functions, 56.56% variables, replace Any with precise library types Complete type annotations: 100% functions, 56.56% variables, eliminate 25+ Any types Feb 4, 2026
@bact
bact merged commit 460bd74 into dev Feb 4, 2026
20 of 33 checks passed
@bact
bact deleted the copilot/add-type-hints-to-submodules-one-more-time branch February 4, 2026 07:35
Copilot stopped work on behalf of bact due to an error February 4, 2026 09:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactoring a technical improvement which does not add any new features or change existing features.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants