如何在 Python 中指定模块作为类型提示?

问题描述 投票:0回答:2

我正在使用 Python 和 Type Hints 以及库

typing
types
,并且无法在没有错误的情况下完成以下代码:

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__}")

目前我遇到错误:

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

我也用

Any
尝试过,然后得到了这个,这也好不到哪儿去:

error: Incompatible types in assignment (expression has type "str", variable has type "list[str]")  [assignment]
error: "list[Any]" has no attribute "__version__"  [attr-defined]
python jupyter-notebook type-hinting
2个回答
0
投票

代码中的问题在于 zip 迭代的变量名称。您有类型提示变量 i 和 j,但对循环迭代变量使用相同的名称,导致类型不匹配。只需重命名其中一个,相信问题就会解决。


0
投票

模块的正确类型提示是 ModuleType,您已经从 types 模块导入。尝试使用变量名称以避免混淆。

试试这个:

from typing import List, ModuleType
import numpy as np
import pandas as pd

modules: List[str]
module_instances: List[ModuleType]

for module, module_instance in zip(['numpy', 'pandas'], [np, pd]):
    print(f"{module} used in this code is version {module_instance.__version__}")
© www.soinside.com 2019 - 2024. All rights reserved.