gpt4 book ai didi

Python更改异常可打印输出,例如重载__builtins__

转载 作者:行者123 更新时间:2023-12-03 17:08:14 25 4
gpt4 key购买 nike

我正在寻找一种方法将异常的可打印输出更改为愚蠢的消息,以了解有关 python 内部结构的更多信息(并与 friend 搞混;),但到目前为止还没有成功。
考虑以下代码

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____str__ ,但似乎是 print函数使用其他东西,即使在阅读 BaseException 的所有属性时我也找不到这些东西。通过 print(dir(BaseException)) .
    谁能告诉我什么是 print请在这种情况下使用?
    [编辑]
    要添加更多上下文:
    我试图解决的问题一开始是为了和一个程序员 friend 开玩笑,但现在成为我了解更多 python 内部结构的挑战。
    我没有试图解决真正的业务问题,我只是想更深入地了解 Python 中的事物。
    我很困惑 print(exc)不会使用 BaseException.__repr____str__实际上。
    [/编辑]

    最佳答案

    简介
    关于为什么你甚至想做你想做的事,我会采用更批判的方法。
    Python 为您提供了处理特定异常的能力。这意味着如果您遇到业务问题,您将使用特定的异常类并为该特定情况提供自定义消息。现在,记住这一段,让我们继续前进,我稍后会提到这一点。

    TL; 博士
    现在,让我们自上而下:
    except Exception 捕获各种错误如果想让你捕获让我们说一个变量名错误,通常不是一个好主意。你会使用 except NameError反而。你真的没有什么可以添加到它的,这就是为什么它有一个完美描述问题的默认消息。因此,假设您会按原样使用它。这些被称为 具体的异常(exception)。
    现在,根据您的具体情况,请注意别名 as exc .通过使用别名,您可以访问传递给异常对象的参数,包括默认消息。

    try:
    x # is not defined
    except NameError as exc:
    print(exc.args)
    运行该代码(我把它放在 app.py 中),你会看到:
    $ python app.py
    ("name 'x' is not defined",)
    这些 args作为一个系列(列表,或者在这种情况下是一个元组的不可变列表)传递给异常。
    这导致了可以轻松地将参数传递给异常的构造函数 ( __init__ ) 的想法。在你的情况下 "name 'x' is not defined"被作为参数传递。
    只需提供自定义消息,您就可以利用此优势轻松解决问题,例如:
    try:
    x # is not defined
    except NameError as exc:
    your_custom_message = "the name 'x' you suggested is not yet defined, my lord. Improve your coding skills"
    # Now, you can handle it based on your requirement:
    # print(your_custom_message)
    # print(NameError(your_custom_message))
    # raise NameError(your_custom_message)
    # raise NameError(your_custom_message) from exc
    输出现在就是您想要实现的目标。
    $ python app.py
    the name 'x' you suggested is not yet defined, my lord. Improve your coding skills

    还记得我说稍后引用的第一段吗?我提到为特定案例提供自定义消息。如果您在想要处理与您的产品相关的特定变量的名称错误时构建自己的库,则您假设您的用户将使用您的代码可能会引发 NameError 异常。他们很可能会用 except Exception as exc 捕获它或 except NameError as exc .当他们这样做时 print(exc) ,他们现在会看到您的消息。

    摘要
    我希望这对您有意义,只需提供一条自定义消息并将其作为参数传递给 NameError或者干脆打印出来。 IMO,最好将它与为什么要使用所使用的东西一起学习。

    关于Python更改异常可打印输出,例如重载__builtins__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64611050/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com