Skip to content

Replace Any type annotations with specific types and remove redundant type annotation reassignments - #1280

Merged
bact merged 16 commits into
devfrom
copilot/refactor-any-type-annotations
Feb 4, 2026
Merged

Replace Any type annotations with specific types and remove redundant type annotation reassignments#1280
bact merged 16 commits into
devfrom
copilot/refactor-any-type-annotations

Conversation

Copilot AI commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

What do these changes do

Removes redundant type annotations from instance-level assignments when type is already declared at class level. Affects 14 classes across 10 files with 60+ redundant annotations eliminated.

What was wrong

Type annotations were duplicated at both class and instance levels, violating PEP 484 best practices:

class ChatBotModel:
    history: list[tuple[str, str]]  # Class level
    
    def __init__(self):
        self.history: list[tuple[str, str]] = []  # Redundant reassignment

This pattern appeared in:

  • FastTextEncoder, Words_Spelling_Correction (words_spelling_correction.py)
  • ThaiTransliterator, Encoder, Attn, AttentionDecoder (thai2rom.py)
  • _ResponseWrapper (corpus/core.py)
  • ChatBotModel (chat/core.py)
  • GzipModel (classify/param_free.py)
  • WngchanBerta_ONNX (tag/wangchanberta_onnx.py)
  • ThaiNameTagger (wangchanberta/core.py)
  • CRFchunk (tag/crfchunk.py)

How this fixes it

Keeps type annotation only at class level, removes from instance assignments:

class ChatBotModel:
    history: list[tuple[str, str]]
    
    def __init__(self):
        self.history = []  # Type inferred from class annotation

Verified with mypy - no new type errors introduced.

Your checklist for this pull request

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

Find type annotations with Any and try to scope it down, providing a more specific and precise type.

It is possible to find type information from the inspection of the library a runtime (required installation) and it is also possible to analyse the source code of the library to obtain the type informaton.

Open source library tend to have source code available on the internet, for example in GitHub. Find information about library's source code repo location from PyPI website or from pyproject.toml/setup.cfg/setup.py metadata in the pip package.

Break job into smaller batches and iterate until complete.


✨ 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 and others added 7 commits February 4, 2026 18:41
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
…ctor

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>
Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title [WIP] Refactor type annotations using more specific types Replace Any type annotations with specific types Feb 4, 2026
Copilot AI requested a review from bact February 4, 2026 18:59
@bact

bact commented Feb 4, 2026

Copy link
Copy Markdown
Member

@copilot Do not use A | B union syntax. Use Union[] and Optional[] for strict compatibility with Python 3.9 - to make sure the inspection tools can work correctly.

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

Copilot AI commented Feb 4, 2026

Copy link
Copy Markdown
Contributor Author

@copilot Do not use A | B union syntax. Use Union[] and Optional[] for strict compatibility with Python 3.9 - to make sure the inspection tools can work correctly.

Replaced all pipe union syntax (|) with Union[] and Optional[] for Python 3.9 compatibility. Changes made in:

  • benchmarks/word_tokenization.py: int | strUnion[int, str]
  • tag/crfchunk.py: str | boolUnion[str, bool]

Commit: d0d030e

@bact bact added the refactoring a technical improvement which does not add any new features or change existing features. label Feb 4, 2026
@bact bact modified the milestones: 53, 5.3 Feb 4, 2026
@coveralls

coveralls commented Feb 4, 2026

Copy link
Copy Markdown

Coverage Status

coverage: 64.79% (+0.004%) from 64.786%
when pulling cc24a14 on copilot/refactor-any-type-annotations
into 8a188f2 on dev.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request improves type safety by replacing 28+ Any type annotations with specific types across 16 files. The changes include using proper types from third-party libraries (transformers, fastai, nltk, epitran), creating type aliases for complex unions, and introducing a TypedDict for structured return values. The PR correctly uses Union[] and Optional[] syntax for Python 3.9 compatibility.

Changes:

  • Replaced Any with specific types from third-party libraries (transformers.Pipeline, fastai.Learner/DataBunch, nltk.Synset, epitran.Epitran, argparse.Namespace)
  • Created NEREngineType type alias for complex Union type in named entity recognition
  • Created CorefResultDict TypedDict for structured coreference resolution results
  • Refined dictionary type annotations from dict[str, Any] to more specific dict[str, Union[str, bool]] and dict[str, Union[int, str]]
  • Eliminated mypy errors across all affected modules (from 11-18 errors per module down to 0)

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
pythainlp/word_vector/core.py Changed tokenizer type from Any to Callable[[str], list[str]]
pythainlp/ulmfit/core.py Added fastai types: Learner and DataBunch
pythainlp/transliterate/ipa.py Changed epitran type from Any to epitran._epitran.Epitran
pythainlp/tag/unigram.py Refined dict types from dict[str, Any] to dict[str, str] for POS taggers
pythainlp/tag/named_entity.py Created NEREngineType type alias and updated engine types
pythainlp/tag/crfchunk.py Refined feature dict type from dict[str, Any] to dict[str, Union[str, bool]]
pythainlp/summarize/keybert.py Changed pipeline type from Any to transformers.pipelines.base.Pipeline
pythainlp/phayathaibert/core.py Changed model type from Any to Pipeline
pythainlp/generate/thai2fit.py Added Path and Learner types from fastai
pythainlp/coref/_fastcoref.py Created CorefResultDict TypedDict and added CorefResult type
pythainlp/cli/tokenize.py Changed args type from Any to argparse.Namespace
pythainlp/cli/tag.py Changed args type from Any to argparse.Namespace
pythainlp/chat/core.py Changed model type from Any to WangChanGLM
pythainlp/benchmarks/word_tokenization.py Refined dict return types to dict[str, Union[int, str]]
pythainlp/augment/wordnet.py Changed synset type from Any to nltk.corpus.reader.wordnet.Synset
build_tools/analysis/output/type_hint_analysis.json Updated type analysis metrics showing elimination of mypy errors

Comment thread pythainlp/tag/named_entity.py
Comment thread pythainlp/tag/named_entity.py Outdated
Comment thread pythainlp/transliterate/ipa.py Outdated
Comment thread pythainlp/benchmarks/word_tokenization.py
@bact

bact commented Feb 4, 2026

Copy link
Copy Markdown
Member

@copilot apply changes based on the comments in this thread

- Add None to NEREngineType to match engine assignment
- Remove redundant type annotation in NNER.__init__
- Use public epitran.Epitran instead of private _epitran module
- Convert numpy integers to Python int for accurate type annotations

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

Copilot AI commented Feb 4, 2026

Copy link
Copy Markdown
Contributor Author

@copilot apply changes based on the comments in this thread

Applied all suggested changes from the review:

  1. named_entity.py:57 - Added None to NEREngineType Union to match line 66 assignment
  2. named_entity.py:157 - Removed redundant type annotation in NNER.init
  3. transliterate/ipa.py:16 - Changed to public epitran.Epitran API instead of private epitran._epitran.Epitran
  4. benchmarks/word_tokenization.py:136 - Converted all numpy integer types to Python int with explicit int() conversions

Commit: d79928c

Comment thread pythainlp/chat/core.py Outdated
The model attribute already has a type annotation at the class level (line 16), so the type annotation in the assignment (line 54) is redundant and should be removed per Python best practices.

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI and others added 2 commits February 4, 2026 21:25
Fixed redundant type annotations in 8 files where attributes were declared at class level and then unnecessarily re-annotated during assignment in __init__ or other methods. This follows Python typing best practices and avoids annotation redundancy.

Files modified:
- pythainlp/spell/words_spelling_correction.py
- pythainlp/transliterate/thai2rom.py
- pythainlp/corpus/core.py
- pythainlp/chat/core.py
- pythainlp/classify/param_free.py
- pythainlp/tag/wangchanberta_onnx.py
- pythainlp/wangchanberta/core.py
- pythainlp/tag/crfchunk.py

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Removed redundant type annotations from __init__ methods in:
- Encoder, Attn, and AttentionDecoder classes in thai2rom.py
- Words_Spelling_Correction class in words_spelling_correction.py

All these classes already had type annotations at the class level, making the instance-level annotations redundant.

Co-authored-by: bact <128572+bact@users.noreply.github.com>
Copilot AI changed the title Replace Any type annotations with specific types Remove redundant type annotation reassignments Feb 4, 2026
@bact
bact requested a review from Copilot February 4, 2026 22:14
@bact
bact marked this pull request as ready for review February 4, 2026 22:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 22 out of 22 changed files in this pull request and generated 1 comment.

Comment thread pythainlp/transliterate/thai2rom.py Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@sonarqubecloud

sonarqubecloud Bot commented Feb 4, 2026

Copy link
Copy Markdown

@bact
bact merged commit f22c110 into dev Feb 4, 2026
22 of 32 checks passed
@bact
bact deleted the copilot/refactor-any-type-annotations branch February 4, 2026 22:24
@bact bact changed the title Remove redundant type annotation reassignments Replace Any type annotations with specific types and remove redundant type annotation reassignments Feb 4, 2026
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.

4 participants