我是一个包的次要贡献者,人们打算这样做(Foo.Bar.Bar
是一个类):
>>> from Foo.Bar import Bar
>>> s = Bar('a')
有时人们会错误地这样做(Foo.Bar
是一个模块):
>>> from Foo import Bar
>>> s = Bar('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
这看起来很简单,但用户仍然无法调试它,我想让它更简单。我无法更改 Foo
或 Bar
的名称,但我想添加一个信息更丰富的回溯,例如:
TypeError("'module' 对象不可调用,也许你打算调用 'Bar.Bar()'")
我读了Callable modules问答,我知道我不能将 __call__
方法添加到模块(而且我不想为此将整个模块包装在一个类中)。无论如何,我不希望模块可调用,我只想要自定义回溯。是否有适用于 Python 3.x 和 2.7+ 的干净解决方案?
最佳答案
将此添加到 Bar.py
的顶部:(基于 this question)
import sys
this_module = sys.modules[__name__]
class MyModule(sys.modules[__name__].__class__):
def __call__(self, *a, **k): # module callable
raise TypeError("'module' object is not callable, perhaps you meant to call 'Bar.Bar()'")
def __getattribute__(self, name):
return this_module.__getattribute__(name)
sys.modules[__name__] = MyModule(__name__)
# the rest of file
class Bar:
pass
注意:使用 python3.6 & python2.7 测试。
关于python - 改变不可调用模块的回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51086846/