python - 改变不可调用模块的回溯

标签 python python-3.x python-2.7 exception module

我是一个包的次要贡献者,人们打算这样做(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

这看起来很简单,但用户仍然无法调试它,我想让它更简单。我无法更改 FooBar 的名称,但我想添加一个信息更丰富的回溯,例如:

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/

相关文章:

python - 如何仅将一个文件的内容差异复制到另一个文件?

python从另一个列表中删除列表的元素,其中两个列表中的项目多次出现

python requests.get() InvalidSchema 错误

python-2.7 - 从日期时间中提取周(Python Pandas)

python - 使用 Scikit-learn 使用日期变量进行回归

python - Django - 为每个模型对象生成随机、唯一的 slug 字段

python - 为什么 'é'和 'é'编码成不同的字节?

python-3.x - 如何通过 selenium python 以文本区域形式(在 HTML 标记中)添加文本?

python - tensorflow 中边界框的坐标

javascript - PostgreSQL (pgAdmin) 和跨站点 cookie 警告