本文介绍了检查模块名称除'ImportError'外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try:
   import MySQLdb
   # some action
except ImportError as err:
   # fallback code

PyCharm给出了一个代码检查警告:

PyCharm gives a code inspection warning on that:

此检查检测到应该解析但不能解析的名称。由于动态调度和鸭型打字,这在有限但有用的情况下是可能的。顶级和类级别的项目比实例项目更好。

This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.

好的,我以为这个警告是合理的,因为回退代码假定'MySQLdb'没有安装,而可能是一些不同的错误,刚刚引发了ImportError。所以我使用的东西如下:

Ok, I thought the warning is reasonable, because the fallback code assumes that 'MySQLdb' is not installed, while it could be some different error that just raised ImportError. So I used something like:

try:
   import MySQLdb
   # some action
except ImportError as err:
   if "MySQLdb" in repr(err):
       # fallback code
   else:
       raise

PyCharm警报仍然存在,但它可能只是PyCharm问题(Google显示此类检查的问题)

The PyCharm alert is still exists, but It could be just a PyCharm issue (google shows issues with such inspections)

问题:

Questions:


  1. 真的值得检查当你ImportError除外?即使在简单的情况下(某些动作之后导入MySQLdb )?

如果值得检查,上面的例子是正确的方法吗?如果没有 - 正确的方式是什么?

If it worth checking, Is the above example the right way to do it? If no - what is the right way?

PS MySQLdb只是一个例子一个可以在系统中缺少的模块。

P.S. MySQLdb is just an example of a module that could be absent in the system.

推荐答案

我认为你误解了警告,如果你没有定义一个变量 MySQLdb 在except块中,稍后当您尝试使用该模块时,您将获得一个 NameError

I think you misunderstood the warning, if you do not define a variable called MySQLdb in the except block then later on when you try to use the module you would get a NameError:

try:
    import foo
except ImportError:
    pass

foo.say_foo() #foo may or may not be defined at this point!

如果模块仅用于 try:子句那么这没有问题。但是对于更一般的情况,检查器希望您在除了块中定义变量:

If the module is only used in the try: clause then this is no issue. But for the more general case the checker expects you to define the variable in the except block:

try:
    import foo
except ImportError:
    foo = None  #now foo always exists

if foo: #if the module is present
    foo.say_foo()
else:
    print("foo") #backup use

这篇关于检查模块名称除'ImportError'外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 23:00
查看更多