gpt4 book ai didi

python - 查找所有内置异常的简单函数在直接运行时有效,但在用作导入模块时失败,不提供回溯

转载 作者:行者123 更新时间:2023-11-30 22:24:10 25 4
gpt4 key购买 nike

我有一个函数,应该生成所有内置异常的元组(用于 except (Exception1, Exception2, etc...) as error: 形式)和当我正常运行它时,它工作得很好。

def get_exceptions():

exceptionList = []

for item in dir(__builtins__):
if item.find('Error') != -1:
exec('exceptionList.append({})'.format(item))

return tuple(exceptionList)

if __name__ == '__main__':
print(get_exceptions())

运行时:

(<class 'ArithmeticError'>, <class 'AssertionError'>, <class 'AttributeError'>, <class 'BlockingIOError'>, <class 'BrokenPipeError'>, <class 'BufferError'>, <class 'ChildProcessError'>, <class 'ConnectionAbortedError'>, <class 'ConnectionError'>, <class 'ConnectionRefusedError'>, <class 'ConnectionResetError'>, <class 'EOFError'>, <class 'OSError'>, <class 'FileExistsError'>, <class 'FileNotFoundError'>, <class 'FloatingPointError'>, <class 'OSError'>, <class 'ImportError'>, <class 'IndentationError'>, <class 'IndexError'>, <class 'InterruptedError'>, <class 'IsADirectoryError'>, <class 'KeyError'>, <class 'LookupError'>, <class 'MemoryError'>, <class 'NameError'>, <class 'NotADirectoryError'>, <class 'NotImplementedError'>, <class 'OSError'>, <class 'OverflowError'>, <class 'PermissionError'>, <class 'ProcessLookupError'>, <class 'ReferenceError'>, <class 'RuntimeError'>, <class 'SyntaxError'>, <class 'SystemError'>, <class 'TabError'>, <class 'TimeoutError'>, <class 'TypeError'>, <class 'UnboundLocalError'>, <class 'UnicodeDecodeError'>, <class 'UnicodeEncodeError'>, <class 'UnicodeError'>, <class 'UnicodeTranslateError'>, <class 'ValueError'>, <class 'OSError'>, <class 'ZeroDivisionError'>)

这正是我想要的。但是,在下面,通过 shell,

>>> import list_exceptions
>>> list_exceptions.get_exceptions()
()

什么也没发生。

即使在文件中:

import list_exceptions
print(list_exceptions.get_exceptions())

我得到:

()

这看起来很奇怪。任何帮助都会很棒!顺便说一句,我看了这些,它们与我的想法并没有真正相关。
import fails when running python as script, but not in iPython?
http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html

如果您有任何疑问,请提出:)

最佳答案

您的方法的根本问题是您依赖于两个不应该依赖的东西。第一个是dir ,不应依赖其行为,因为它的存在主要是为了帮助在交互式 shell 中进行调试。来自 docs :

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

...

Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

此外,您使用 __builtins__变量,它是一个实现细节同样来自 docs :

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

本质上,你依赖的是两个不可靠的东西。请注意,您的情况实际发生是,当您直接运行该模块时,它返回实际的 builtins模块,但是,当导入模块时,__builtins__包含“此模块的值__dict__”。一些调试打印可以说明这一点:

# builtinstest.py
def get_exceptions():

print(type(__builtins__))
print(dir(__builtins__))

从交互式解释器中:

>>> import builtinstest
>>> builtinstest.get_exceptions()
<class 'dict'>
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

所以当你调用dir时在dict上对象,它只是返回可从 dict-object 中自省(introspection)的属性,例如copy , fromkeys , get , items和所有其他dict方法。解决方案是使用 builtins模块并且不要使用 dir ,使用vars (它只返回 __dict__ 属性),因为您需要模块对象的属性。

最后,你的方法 exec不好。如果你想明智地执行此操作,请检查它是否是 BaseException 的子类。 ,它是所有内置异常的父类,因此来自 the docs :

exception BaseException

The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception).

所以类似:

import builtins
def get_exceptions_sanely():
exception_list = []
for obj in vars(builtins).values():
if isinstance(obj, type) and issubclass(obj, BaseException):
exception_list.append(obj)
return tuple(exception_list)

做你想要完成的事情。请注意,这会直接迭代,因此您最终不会使用类似 eval 的内容。或exec ,在本例中这是一种滥用。请注意,这会捕获每个内置异常,例如警告(例如 BytesWarning )以及更深奥的内容,例如 SystemExit

终于

仅仅因为您可以这样做,并不意味着您应该。您声明的目的是:

I have a function that is supposed to generate a tuple of all built-in exceptions, (for use in the except (Exception1, Exception2, etc...)
as error:
form)

好吧,你可以使用 except BaseException as error而不是首先通过繁琐的步骤查找这些异常(事实上, except <something> 本质上是检查 <something> issubclass 是否引发了任何错误。从根本上来说,很少有任何充分的理由拥有如此广泛的 except 子句。您应该始终 try catch 尽可能窄的异常。

关于python - 查找所有内置异常的简单函数在直接运行时有效,但在用作导入模块时失败,不提供回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897391/

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