- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个函数,应该生成所有内置异常的元组(用于 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...)
form)
as error:
好吧,你可以使用 except BaseException as error
而不是首先通过繁琐的步骤查找这些异常(事实上, except <something>
本质上是检查 <something>
issubclass
是否引发了任何错误。从根本上来说,很少有任何充分的理由拥有如此广泛的 except
子句。您应该始终 try catch 尽可能窄的异常。
关于python - 查找所有内置异常的简单函数在直接运行时有效,但在用作导入模块时失败,不提供回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897391/
问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionally与 CompletableFuture#supplyAsync 一起.这是行不通的: priva
对于 Web 服务,我们通常使用 maven-jaxb2-plugin 生成 java bean,并在 Spring 中使用 JAXB2 编码。我想知道如何处理 WSDL/XSD 中声明的(SOAP-
这个问题已经有答案了: Array index out of bound behavior (10 个回答) 已关闭 8 年前。 我对下面的 C 代码感到好奇 int main(){
当在类的开头使用上下文和资源初始化 MediaPlayer 对象时,它会抛出 NullPointer 异常,但是当在类的开头声明它时(因此它是 null),然后以相同的方式初始化它在onCreate方
嘿 我尝试将 java 程序连接到 REST API。 使用相同的代码部分,我在 Java 6 中遇到了 Java 异常,并且在 Java 8 中运行良好。 环境相同: 信任 机器 unix 用户 代
我正在尝试使用 Flume 和 Hive 进行 Twitter 分析。为了从 twitter 获取推文,我在 flume.conf 文件中设置了所有必需的参数(consumerKey、consumer
我在 JavaFX 异常方面遇到一些问题。我的项目在我的 Eclipse 中运行,但现在我的 friend 也尝试访问该项目。我们已共享并直接保存到保管箱文件夹中。但他根本无法让它发挥作用。他在控制台
假设我使用 blur() 事件验证了电子邮件 ID,我正在这样做: $('#email').blur(function(){ //make ajax call , check if dupli
我这样做是为了从 C 代码调用非托管函数。 pCallback 是一个函数指针,因此在托管端是一个委托(delegate)。 [DllImport("MyDLL.dll")] public stati
为什么这段代码是正确的: try { } catch(ArrayOutOfBoundsException e) {} 这是错误的: try { } catch(IOException e) {} 这段
我遇到了以下问题:有导出函数的DLL。 代码示例如下:[动态链接库] __declspec(dllexport) int openDevice(int,void**) [应用] 开发者.h: __de
从其他线程,我知道我们不应该在析构函数中抛出异常!但是对于下面的例子,它确实有效。这是否意味着我们只能在一个实例的析构函数中抛出异常?我们应该如何理解这个代码示例! #include using n
为什么需要异常 引出 public static void main(String[
1. Java的异常机制 Throwable类是Java异常类型的顶层父类,一个对象只有是 Throwable 类的(直接或者间接)实例,他才是一个异常对象,才能被异常处理机制识别。JDK中内
我是 Python 的新手,我对某种异常方法的实现有疑问。这是代码(缩写): class OurException(Exception): """User defined Exception"
我已经创建了以下模式来表示用户和一组线程之间的关联,这些线程按他们的最后一条消息排序(用户已经阅读了哪些线程,哪些没有): CREATE TABLE table(user_id bigint, mes
我正在使用 Python 编写一个简单的自动化脚本,它可能会在多个位置引发异常。在他们每个人中,我都想记录一条特定的消息并退出程序。为此,我在捕获异常并处理它(执行特定的日志记录操作等)后引发 Sys
谁能解释一下为什么这会导致错误: let xs = [| "Mary"; "Mungo"; "Midge" |] Array.iter printfn xs 虽然不是这样: Array.iter pr
在我使用 Play! 的网站上,我有一个管理部分。所有 Admin Controller 都有一个 @With 和一个 @Check 注释。 断开连接后,一切正常。连接后,每次加载页面(任何页面,无论
我尝试连接到 azure 表存储并添加一个对象。它在本地主机上工作得很好,但是在我使用的服务器上我得到以下异常及其内部异常: Exception of type 'Microsoft.Wind
我是一名优秀的程序员,十分优秀!