Python PyCharm 中的错误未使用导入语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21139329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:09:39  来源:igfitidea点击:

False Unused Import Statement in PyCharm?

pythonidepycharm

提问by Mihnea Simian

Given this scenario:

鉴于这种情况:

b.py:

b.py:

import A
# A is unused here

c.py:

c.py:

from b import A
# A is used here

PyCharm complains in b.py that "import A" is an unused import and Optimize imports deletes it, breaking import in c.py

PyCharm 在 b.py 中抱怨“import A”是一个未使用的导入,优化导入将其删除,破坏了 c.py 中的导入

I know these chained imports are not a good practice (although you may use it to implement a facade module), but is it me or is it a PyCharm fail?

我知道这些链式导入不是一个好习惯(尽管您可以使用它来实现外观模块),但是是我还是 PyCharm 失败了?

采纳答案by Bakuriu

As far as I can tell this behaviour is nothandled as an inspection or some other configurable option, which means there is no #noinspection UnusedImport(or equivalent) that can be placed before the imports.

据我所知,这种行为不是作为检查或其他一些可配置选项处理的,这意味着#noinspection UnusedImport在导入之前没有(或等效的)可以放置。

If you don't want to define an unused block where you use those variables there's an other simple and probably better way to achieve what you want:

如果您不想在使用这些变量的地方定义一个未使用的块,还有另一种简单且可能更好的方法来实现您想要的:

#b.py code
import A

# [...] your code


__all__ = ['A', ...]  # *all* the names you want to export

PyCharm is smart enough to look at __all__and avoid removing Aas unused import. However there's a limitation that __all__must be a simple list literal. You cannotdo things like:

PyCharm 足够聪明,可以查看__all__并避免删除A未使用的导入。但是有一个限制,__all__必须是一个简单的列表文字。你不能做这样的事情:

__all__ = ['A'] + [name for name in iterable if condition(name)]

Not even:

甚至不:

x = 'b'
__all__ = ['A', x]

Defining __all__is a best-practice to make your module *-import safe anyway, so is something you should already do.

无论如何,定义__all__是使您的模块*-import 安全的最佳实践,因此您应该已经这样做了。

回答by benselme

You can actually use the PyUnresolvedReferencesmarker to deactivate the inspection for your import statement:

您实际上可以使用PyUnresolvedReferences标记来停用导入语句的检查:

# noinspection PyUnresolvedReferences
import A

Reference: PyCharm bug PY-2240

参考:PyCharm 错误 PY-2240

回答by Peter Zagubisalo

from C import A, B
_ = (A, B); del _

Works for me. I don't like

为我工作。我不喜欢

# noinspection PyUnresolvedReferences

as it would give false negatives in case A cannot be imported. And

因为如果不能导入 A,它会给出假阴性。和

__all__ = ['A', 'B', ...]

is cryptic and is not convenient for refactoring.

是神秘的,不便于重构。