Python __是否为导入时运行两次的模块获取属性?
当使用Python __是否为导入时运行两次的模块获取属性?,python,python-3.x,python-module,getattr,Python,Python 3.x,Python Module,Getattr,当使用\uu getattr\uuu从模块导入对象时,我尝试运行一些逻辑,如下所述: …但逻辑运行了两次。为什么会发生这种情况?我如何才能阻止它 main.py from test import x, y def __getattr__(name: str): print(f"Imported {name}") test.py from test import x, y def __getattr__(name: str): print(f"
\uu getattr\uuu
从模块导入对象时,我尝试运行一些逻辑,如下所述:
…但逻辑运行了两次。为什么会发生这种情况?我如何才能阻止它
main.py
from test import x, y
def __getattr__(name: str):
print(f"Imported {name}")
test.py
from test import x, y
def __getattr__(name: str):
print(f"Imported {name}")
您的
\uuuu getattr\uuuuuu
返回所有属性的无
,包括\uuuuuuu路径
,如果模块具有\uuu路径
属性,则将其视为一个包
对于一个包,从测试导入x,y
需要处理名为test.x
和test.y
的可能子模块。执行此处理的程序首先使用hasattr
来测试test
是否已经具有x
和y
属性:
elif not hasattr(module, x):
...
而hasattr
负责第一次\uuuuGetAttr\uuuuuuuuuuuuuuuuuuuuu('x')
和\uuuuuuuGetAttr\uuuuuuuuuuuuy')
调用
第二个\uuu getattr\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux('x')
和\u
您的\uuuuu getattr\uuuuu
不应为特殊属性返回值,如\uuuuuu path\uuuuu
另外,不相关的,命名模块test
是一个坏主意,因为标准库已经声明了该名称。请将您的代码和输出作为文本发布,而不是屏幕截图。您是否尝试在调用期间检查回溯?@o11c没有回溯,因为代码已成功执行。在详细模式下运行python在本地复制时不会显示任何信息。检查cProfile显示了对测试的5个调用。\uuuuu getattr\uuuuuuu
:5 0.000 0.000 0.000 0.000 test.py:1(\uuu getattr\uuuuuuu)
@C.Nivs dupe显示了如何检查回溯。“你的getattr对所有属性都返回None,包括path”我有什么办法防止这种情况吗?我仍然想让我的逻辑只运行一次,但我不知道如何使hasattr
返回False
对于\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu