我有一个Python项目,我希望应用引用自定义用户定义类的类型提示,而不必导入它们。我的项目越来越大,我觉得应用适当的类型提示会大大增加导入语句的数量。这是一个简化的场景来说明我的痛苦:
在我的 main.py 文件中,希望在处理我的自定义类的函数 my_function 中为变量 x 添加类型提示。来自 myOtherFile.py 的strong> MyCustomClass 。我希望应用类型提示而不必将MyClass导入到main.py。
my_function(x: MyCustomClass):
...
到目前为止,我看到的最好的解决方案是创建一个文件 allCustomClassTypes.py ,如果启用了类型检查以防止循环依赖问题,则该文件将导入整个项目中的所有自定义类:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from myOtherFile1 import MyCustomClass1
from myOtherFile2 import MyCustomClass2
from myOtherFile3 import MyCustomClass3
...
然后在每个文件中应用此导入语句:
from allCustomClassTypes import *
但是我不太喜欢这种方法,希望有更好的方法。有谁能更好地解决我所描述的问题?