为什么异常处理不检查库的存在

发布于 2024-12-19 00:17:07 字数 258 浏览 0 评论 0原文

我不明白为什么 python(至少 2.7)不验证错误的异常处理机制。

示例:

try:
    some code selecting data from pymongo
except pymongo.errors.OperationFailure:
    exception

在这种情况下,如果不是第一次调用异常,python 将不会验证我是否确实导入了 pymongo lib。

知道为什么吗?

I don't understand why python (at least 2.7) is not validating the exception handling mechanism for errors.

Example:

try:
    some code selecting data from pymongo
except pymongo.errors.OperationFailure:
    exception

In this case, if the exception is not called for the first time, python will not validate if I actually did import the pymongo lib.

Any idea why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清风无影 2024-12-26 00:17:07

如果我正确地阅读了您的问题,您想知道为什么 except pymongo.errors.OperationFailure 在加载模块时如果您尚未导入 pymongo 则不会导致错误模块。

与 Python 中的大多数事物一样,except 子句的参数在运行时评估。事实上,它们可以是表达式! Python 在“编译”时不会验证它们,就像它当时不会验证任何其他名称一样。

原因是Python是一种动态语言。导入可以有条件地完成,或者根据“编译”时未知的名称执行,并且模块和其他命名空间可以通过代码替换、修改或删除。因此,在不运行代码的情况下,Python 实际上无法知道 pymongo.errors.OperationFailure 是否是代码执行时的有效名称。

If I'm reading your question right, you want to know why except pymongo.errors.OperationFailure doesn't cause an error when the module is loaded if you haven't already imported the pymongo module.

Like most things in Python, the arguments to except clauses are evaluated at runtime. In fact, they can be expressions! Python does not validate them at "compile" time any more than it validates any other names at that time.

The reason is that Python is a dynamic language. Imports can be done conditionally, or performed based on names that are not known at "compile" time, and modules and other namespaces can be replaced, modified, or removed by code. As a result, Python literally cannot know whether pymongo.errors.OperationFailure is a valid name at that point in your code's execution without running your code.

-残月青衣踏尘吟 2024-12-26 00:17:07

根据 PyMongo 文档,异常 pymongo.errors.OperationFailure 将“在数据库操作失败时引发”。因此,只有在引发此类错误时才会评估您的 except 块。

我假设通过“验证 pymongo 的存在”您指的是这样的东西:

try:
   import pymongo
except:
   print("PyMongo not found!")
   sys.exit(-1)

此方法经常用于提供后备(和向后兼容性)而不是“验证”导入。例如,在 json 编码器/解码器的情况下,我们可以尝试是否有可用的 simplejson 库,并使用 json 库作为后备,如下所示:

try:
   import simplejson as json
except ImportError:
   import json

假设在脚本的开头,您已经有了 import pymongo,我不认为您应该检查或“验证”pymongo 是否已导入: import如果找不到 pymongo 库,pymongo 将会引发 ImportError

According to PyMongo documentation, exception pymongo.errors.OperationFailure will be "raised when a database operation fails". AS such, your exceptblock gets evaluated only when such an error is raised.

I'm assuming that by "validation of pymongo's existence" you are referring to somethine like:

try:
   import pymongo
except:
   print("PyMongo not found!")
   sys.exit(-1)

This method is often used to provide fallbacks (and backwards compatibity) not to "validate" imports. For instance in the case of json encoder/decoder, we can try whether we have simplejson library available and use jsonlibrary as a fallback as follows:

try:
   import simplejson as json
except ImportError:
   import json

Assuming that in the beginning of your script, you already have import pymongo, I don't see a reason why you should be checking or "validating" that pymongo has been imported: import pymongo will already raise an ImportError if pymongo library is not found.

微凉 2024-12-26 00:17:07

首先,pymongo.errors.OperationFailure可以在任何地方定义,不仅可以作为pymongo模块的一部分,还可以作为在同一文件中定义的 pymongo 对象的属性。

因此,在处理异常时,Python 不应检查特定模块是否已导入

但是如果你这样做:

import pymongo

你会看到如果找不到模块,实际上会引发导入错误

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pymongo
ImportError: No module named pymongo

如果我的答案对你来说还不够,并且你想了解更多关于为什么包含 pymongo.errors.OperationFailure 当您第一次运行脚本时,即使您的代码中没有任何 import pymongo 语句,也不会抛出任何错误,然后请参阅<一个href="https://stackoverflow.com/questions/8331267/why-the-exception-handling-is-not-checking-existence-of-library/8331349#8331349">kindall关于Python是一种动态语言的回答。

First of all, pymongo.errors.OperationFailure may be defined anywhere, not only as a part of pymongo module, but also as a property of property of pymongo object defined in the same file.

Thus when handling exceptions Python should not check if specific module has been imported.

But if you do something like that:

import pymongo

you will see that import error is actually raised if module is not found:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pymongo
ImportError: No module named pymongo

If my answer is not enough for you and you want to know more about why inclusion of pymongo.errors.OperationFailure does not throw any error when you run your script for the first time, even though you do not have any import pymongo statement in your code, then please see kindall's answer on Python being a dynamic language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文