Python 应该避免通配符导入吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3615125/
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
Should wildcard import be avoided?
提问by Colin
I'm using PyQt and am running into this issue. If my import statements are:
我正在使用 PyQt 并且遇到了这个问题。如果我的导入语句是:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
then pylint gives hundreds of "Unused import" warnings. I'm hesitant to just turn them off, because there might be other unused imports that are actually useful to see. Another option would be to do this:
然后 pylint 给出了数百个“未使用的导入”警告。我很犹豫是否关闭它们,因为可能还有其他未使用的导入实际上很有用。另一种选择是这样做:
from PyQt4.QtCore import Qt, QPointF, QRectF
from PyQt4.QtGui import QGraphicsItem, QGraphicsScene, ...
and I end up having 9 classes on the QtGui line. There's a third option, which is:
我最终在 QtGui 线上有 9 个课程。还有第三种选择,即:
from PyQt4 import QtCore, QtGui
and then prefix all the classes with QtCore or QtGui whenever I use them.
然后每当我使用它们时,用 QtCore 或 QtGui 为所有类添加前缀。
At this point I'm agnostic as to which one I end up doing in my project, although the last one seems the most painful from my perspective. What are the common practices here? Are there technical reason to use one style over the other?
在这一点上,我不知道我最终在我的项目中做了哪一个,尽管从我的角度来看,最后一个似乎是最痛苦的。这里有哪些常见的做法?使用一种风格而不是另一种风格是否有技术原因?
采纳答案by Alex Martelli
The answer to your question's title is "yes": I recommend never using from ... import *, and I discussed the reasons in another very recent answer. Briefly, qualified names are good, barenames are very limited, so the "third option" is optimal (as you'll be using qualified names, not barenames) among those you present.
您问题标题的答案是“是”:我建议永远不要使用from ... import *,并且我在最近的另一个答案中讨论了原因。简而言之,限定名很好,裸名非常有限,因此在您提供的那些中,“第三种选择”是最佳的(因为您将使用限定名,而不是裸名)。
(Advantages of qualified names wrt barenames include ease of faking/mocking for testing purposes, reduced to nullified risk of unnoticed errors induced by accidental rebinding, ability to "semi-fake" the top name in a "tracing class" for the purpose of logging exactly what you're using and easing such activities as profiling, and so forth -- disadvantages, just about none... see also the last-but-not-least koan in the Zen of Python, import thisat the interactive interpreter prompt).
(限定名称与裸名的优点包括易于伪造/模拟以进行测试,将意外重新绑定引起的未被注意的错误的风险降低到无效,能够“半伪造”“跟踪类”中的顶级名称以进行日志记录正是您正在使用的内容,并简化了诸如分析等活动——缺点,几乎没有……另请参阅 Python 禅宗中的最后但并非最不重要的公案,import this在交互式解释器提示下)。
Equally good, if you grudge the 7 extra characters to say QtCore.whatever, is to abbreviate -- from PyQt4 import QtCore as Crand from PyQt4 import QtGi as Gu(then use Cr.blahand Gu.zorp) or the like. Like all abbreviations, it's a style tradeoff between conciseness and clarity (would you rather name a variable count_of_all_widgets_in_the_inventory, num_widgets, or x? often the middle choice would be best, but not always;-).
同样好,如果你对 7 个额外的字符表示不满QtCore.whatever,那就是缩写 -- from PyQt4 import QtCore as Crand from PyQt4 import QtGi as Gu(然后使用Cr.blahand Gu.zorp)等。像所有的缩写一样,它是简洁性和清晰性之间的一种权衡(你更愿意命名一个变量count_of_all_widgets_in_the_inventory, num_widgets, 还是x? 通常中间的选择是最好的,但并不总是;-)。
BTW, I would not use more than one asclause in a single fromor importstatement (could be confusing), I'd rather have multiple statements (also easier to debug if any import is giving problem, to edit if you change your imports in the future, ...).
顺便说一句,我不会as在一个fromorimport语句中使用多个子句(可能会令人困惑),我宁愿有多个语句(如果任何导入出现问题也更容易调试,如果您将来更改导入,则进行编辑,……)。
回答by luc
Python docsays:
Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practice in production code.
尽管某些模块设计为在您使用 import * 时仅导出遵循某些模式的名称,但在生产代码中仍然被认为是不好的做法。
It can have side effects and be very difficult to debug
它可能有副作用并且很难调试
Personally, I am using importrather than from importbecause I find awful big declarations at the beginning of the file and I think it keeps the code more readable
就个人而言,我使用import而不是from import因为我在文件开头发现了可怕的大声明,我认为它使代码更具可读性
import PyQt4
PyQt4.QtCore
If the module name is too long and can be renamed locally with the askeyword. For example:
如果模块名称太长,可以使用as关键字在本地重命名。例如:
import PyQt4.QtCore as Qc
回答by Tomasz Wysocki
There are also good cases for import *. ie. it's common for Django developers to have many config files and chain them using import *:
也有很好的案例import *。IE。Django 开发人员通常拥有许多配置文件并使用 import * 将它们链接起来:
settings.py:
FOO = 1
BAR = 2
DEBUG = False
test_settings.py:
from settings import *
DEBUG = True
In this case most disadvantages of import *become advantages.
在这种情况下,大多数缺点都import *变成了优点。
回答by sunqiang
import for PyQt4 is a special case.
sometimes I'll choose the "first option" for quick and dirty coding, and turn it to the "second option" when the code grows longer and longer.
namespace collision maybe not a big deal here, I haven't see other package'name starts with a big "Q". and whenever I finish a PyQt4 script. convert"from PyQt4.QtGui import *" to sth. like "
PyQt4 的导入是一个特例。
有时我会选择“第一个选项”进行快速而肮脏的编码,并在代码越来越长时将其转换为“第二个选项”。
命名空间冲突在这里可能没什么大不了的,我没有看到其他包的名称以大“Q”开头。每当我完成 PyQt4 脚本时。将“from PyQt4.QtGui import *”转换为某物。喜欢 ”
from PyQt4.QtGui import (QApplication, QDialog, QLineEdit, QTextBrowser,
QVBoxLayout)
" just FYI, parentheses for multi-line importis handy here.
" 仅供参考,多行导入的括号在这里很方便。
回答by xioxox
I use the "import *" for the PyQt modules I use, but I put them in their own module, so it doesn't pollute the namespace of the user. e.g.
我对我使用的 PyQt 模块使用“import *”,但我将它们放在自己的模块中,因此它不会污染用户的命名空间。例如
In qt4.py:
在 qt4.py 中:
from PyQt4.QtCore import * from PyQt4.QtGui import *
Then use it like this
然后像这样使用它
import qt4 app = qt4.QApplication(...)
回答by Christian Tismer
I am too absolutely against import *in the general case.
In the case of PySide2, one of the rare exceptions applies:
import *在一般情况下,我太绝对反对了。在 的情况下PySide2,罕见的例外之一适用:
from PySide2 import *
is the pattern to import all known modules from PySide2. This
import is very convenient, because the import is always correct.
The constant is computed from the CMAKEgenerator. Very helpful
when quickly trying something in the interactive console, but also in automated testing.
是从 中导入所有已知模块的模式PySide2。这种导入非常方便,因为导入总是正确的。常量是从CMAKE生成器计算出来的。在交互式控制台中快速尝试某些东西时非常有用,而且在自动化测试中也是如此。
For advanced usage, it makes also sense to
use the PySide2.__all__variable directly, which implements this
feature. The elements of PySide2.__all__are ordered by dependency,
so first comes QtCore, then QtGui, QtWidgets, ... and so on.
对于高级用法,PySide2.__all__直接使用实现此功能的变量也是有意义的。的元素PySide2.__all__按依存关系排序,所以先是QtCore,然后是QtGui,QtWidgets, ... 等等。

