我有一个Python包,它有一个可选的[Extras]依赖项,但我希望在所有方法上都坚持类型化.

情况是,在我的档案中,我有这个

class MyClass:

    def __init__(self, datastore: Datastore):  # <- Datastore is azureml.core.Datastore
        ...

    def my_func(self):
        from azureml.core import Datastore
        ...

我从函数内部导入,因为同一文件中还有其他类,在不使用附加组件(附加组件为azureml)时应该导入这些类.

所以这显然是失败的,因为我在导入它之前引用了Datastore.从__init__方法中go 掉Datastore打字显然解决了这个问题.

因此,总的来说,我的问题是,在键入可选(额外)包时,是否可以使用键入,如果可能,如何使用键入.

请注意,在类定义中导入(在class MyClass语句下面)不是有效的解决方案,因为在导入模块时会调用此代码

推荐答案

您可以使用TYPE_CHECKING:

第三方静态类型假定为True的特殊常量 跳棋.在运行时为FALSE.

It is False at runtime:所以它不会影响模块的行为.

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from azureml.core import Datastore


class MyClass:
    def __init__(self, datastore: Datastore):
        ...

    def my_func(self):
        from azureml.core import Datastore
        ...

由于我想实际展示这一点,我将使用operator.itemgetter作为一个实例,因为它对于类型判断器是可识别的,而azureml.core则不能:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from operator import itemgetter


class MyClass:
    def __init__(self, datastore: itemgetter):
        ...

    def my_func(self):
        from operator import itemgetter
        ...


obj1 = MyClass(itemgetter(1))  # line 16
obj2 = MyClass(10)             # line 17

以下是Mypy错误:

main.py:17: error: Argument 1 to "MyClass" has incompatible type "int"; expected "itemgetter[Any]"
Found 1 error in 1 file (checked 1 source file)

这表明它像例外地工作.

Python相关问答推荐

如何在WSL2中更新Python到最新版本(3.12.2)?

SQLAlchemy Like ALL ORM analog

创建可序列化数据模型的最佳方法

多指标不同顺序串联大Pandas 模型

实现神经网络代码时的TypeError

启用/禁用shiny 的自动重新加载

名为__main__. py的Python模块在导入时不运行'

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

剪切间隔以添加特定日期

比Pandas 更好的 Select

Python pint将1/华氏度转换为1/摄氏度°°

GPT python SDK引入了大量开销/错误超时

如何在验证文本列表时使正则表达式无序?

删除特定列后的所有列

PYTHON中的selenium不会打开 chromium URL

为什么在更新Pandas 2.x中的列时,数据类型不会更改,而在Pandas 1.x中会更改?

多个布尔条件的`jax.lax.cond`等效项

对列中的数字进行迭代,得到n次重复开始的第一个行号

如何在开始迭代自定义迭代器类时重置索引属性?

给定y的误差时,线性回归系数的计算误差