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]
The answer was in the comments, but new answers did not get it right so I thought of posting it myself instead. Turns out I was itterating through the objects in question (str's and modules) in a list, not itterating though a list of them! I had to make that explicit in the code:
i: str
j: ModuleType
for i, j in zip(
['numpy', 'pandas'],
[np, pd]):
print(f"{i} used in this code is version {j.__version__}")