我正在寻找一种方法将异常的可打印输出更改为愚蠢的消息,以便了解有关 python 内部结构的更多信息(并与朋友搞混;),到目前为止没有成功。
考虑下面的代码
try:
x # is not defined
except NameError as exc:
print(exc)
代码应输出name 'x' is not defined
我希望将输出更改为the name 'x' you suggested is not yet defined, my lord. Improve your coding skills
.
到目前为止,我明白你无法改变__builtins__
因为它们是作为 C 代码“嵌入”的,除非:
- 您使用forbiddenfruit.curse方法添加/更改任何对象的属性
- 您手动覆盖对象的字典
我尝试了两种解决方案,但没有成功:
禁果解决方案:
from forbiddenfruit import curse
curse(BaseException, 'repr', lambda self: print("Test message for repr"))
curse(BaseException, 'str', lambda self: print("Test message for str"))
try:
x
except NameError as exc:
print(exc.str()) # Works, shows test message
print(exc.repr()) # Works, shows test message
print(repr(exc)) # Does not work, shows real message
print(str(exc)) # Does not work, shows real message
print(exc) # Does not work, shows real message
字典覆盖解决方案:
import gc
underlying_dict = gc.get_referents(BaseException.__dict__)[0]
underlying_dict["__repr__"] = lambda self: print("test message for repr")
underlying_dict["__str__"] = lambda self: print("test message for str")
underlying_dict["args"] = 'I am an argument list'
try:
x
except NameError as exc:
print(exc.__str__()) # Works, shows test message
print(exc.__repr__()) # Works, shows test message
print(repr(exc)) # Does not work, shows real message
print(str(exc)) # Does not work, shows real message
print(exc) # Does not work, shows real message
AFAIK,使用print(exc)
应该依赖于__repr__
or __str__
,但似乎print
函数使用了其他东西,即使阅读了它的所有属性,我也找不到它BaseException
via print(dir(BaseException))
。
谁能告诉我什么是print
请问在这种情况下使用吗?
[EDIT]
添加更多上下文:
我试图解决的问题一开始只是为了和一位程序员朋友开个玩笑,但现在变成了我更多地了解 python 内部原理的挑战。
我没有试图解决真正的业务问题,我只是想更深入地了解 Python 中的事物。我很困惑print(exc)
不会利用BaseException.__repr__
or __str__
实际上。
[/EDIT]