[Python] How can I specify a module as a Type Hint in Python?

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python and Type Hints with the libraries typing and types, and cannot get through the following code with out errors:

    import numpy as np
    import pandas as pd
    import nb_mypy
    %load_ext nb_mypy
    %reload_ext nb_mypy
    %nb_mypy On
    %nb_mypy DebugOff
    from typing import Tuple, Union, Dict, List, Any
    from types import ModuleType # FrameType, TracebackType

    i: List[str]
    j: List[ModuleType] # I couldn't find the Type Hint for modules...

    for i, j in zip(
    ['numpy', 'pandas'],
    [np, pd]):
    print(f"{i} used in this code is version {j.__version__}")


    At the moment I get errors:

    error: Incompatible types in assignment (expression has type "str", variable has type "list[str]") [assignment]
    error: "list[Module]" has no attribute "__version__" [attr-defined]


    I tried it with Any too, and got this instead, which is no better:

    error: Incompatible types in assignment (expression has type "str", variable has type "list[str]") [assignment]
    error: "list[Any]" has no attribute "__version__" [attr-defined]

    Continue reading...

Compartilhe esta Página