用户定义类的Python类型提示,无需导入

问题描述

我有一个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 *

但是我不太喜欢这种方法,希望有更好的方法。有谁能更好地解决我所描述的问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...