Skip to content

refactor: Improve Type Hinting and Static Analysis #71 - #96

Open
Yousa-Mirage wants to merge 10 commits into
J535D165:mainfrom
Yousa-Mirage:Yousa-Mirage/issue71
Open

Yousa-Mirage wants to merge 10 commits into
J535D165:mainfrom
Yousa-Mirage:Yousa-Mirage/issue71

Conversation

@Yousa-Mirage

@Yousa-Mirage Yousa-Mirage commented Feb 6, 2026 •

Copy link
Copy Markdown

Close #71

Description

This PR introduces comprehensive static type annotations to pyalex/api.py. The primary goal is to resolve existing Pylance/MyPy errors, enable intelligent IDE autocompletion, and prevent type-related bugs during development, all without altering the existing runtime logic.

The codebase now fully supports Python 3.8+ type checking standards, ensuring that entities like Works, Authors, and configuration objects are correctly inferred by static analysis tools.

Before

图片

After

Please see the inlay hints of variable types:

图片

Runtime Logic Integrity

  • No functional changes: The core logic for API requests, pagination, and data handling remains exactly the same.
  • Dynamic behavior preserved: While static checks are stricter, runtime flexibility (e.g., dynamic dictionary attributes in AlexConfig) is preserved using if not TYPE_CHECKING blocks.

Key Changes

  1. Generic Typing Implementation (Generic[T]):
    • Introduced TypeVar("T") bound to OpenAlexEntity.
    • Refactored BaseOpenAlex, OpenAlexResponseList, and Paginator to be generic classes.
    • Result: Calls like Works().get() now correctly return OpenAlexResponseList[Work], allowing IDEs to autocomplete methods specific to Work (e.g., .ngrams(), .pdf) while iterating.
  2. AlexConfig Hardening:
    • Added explicit type annotations for all configuration attributes (e.g., email, api_key).
    • Defined an explicit __init__ method. This allows static checkers to catch typos in configuration keys (e.g., config.emaiil="...") will now raise a static error).
    • Used if not TYPE_CHECKING to hide the dynamic __getattr__/__setattr__ methods from static analyzers while keeping them active at runtime.
  3. Dictionary Inheritance Fixes:
    • Updated OpenAlexEntity and AlexConfig to inherit from Dict[str, Any] instead of plain dict.
    • Result: Resolves Pylance errors such as "Object of type 'Work' is not subscriptable" or generic "Unknown type" warnings.
  4. Strict Parameter Typing:
    • Utilized Literal["cursor", "page"] for pagination methods to prevent invalid string arguments.
    • Utilized typing.cast and Optional to handle default values safely without confusing type checkers.
  5. Packaging & PEP 561 Compliance:
    • Added the pyalex/py.typed marker file.
    • Updated pyproject.toml (specifically [tool.setuptools.package-data]) to include this file in the build distribution.
    • Result: Ensures that when users pip install pyalex, their type checkers will automatically recognize and utilize the package's type hints.

Benefits

  • Intelligent Autocompletion: Users will now see accurate method and attribute suggestions for specific entities (Work, Author, Source, etc.).
  • Error Detection: Static analysis tools can now catch common errors (e.g., invalid config keys, wrong types passed to filters) before runtime.
  • Zero Pylance/MyPy Errors: Clears the "noise" in VS Code problems tab, making genuine bugs easier to spot.
  • Python 3.8 Compatibility: All type hints use compatible syntax (e.g., Union, Optional instead of | operator) to maintain the project's minimum version requirement.

Verification

  • Verified that pytest passes with no failures.
  • Verified that both Pylance and ty reports zero errors in api.py and test scripts except the explicit type error get(per_page="100") test.

@Yousa-Mirage Yousa-Mirage changed the title Add type lint in api.py with py3.8 syntax refactor: Comprehensive Type Hinting and Static Analysis Improvements Feb 6, 2026
@Yousa-Mirage Yousa-Mirage changed the title refactor: Comprehensive Type Hinting and Static Analysis Improvements refactor: Improve Type Hinting and Static Analysis #71 Feb 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Type the library

1 participant