是否应该避免使用通配符?

Col*_*lin 48 python pyqt pylint pyqt4 python-import

我正在使用PyQt并遇到了这个问题.如果我的import语句是:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
Run Code Online (Sandbox Code Playgroud)

然后pylint给出了数百个"未使用的导入"警告.我很犹豫要把它们关闭,因为可能有其他未使用的导入实际上很有用.另一种选择是这样做:

from PyQt4.QtCore import Qt, QPointF, QRectF
from PyQt4.QtGui import QGraphicsItem, QGraphicsScene, ...
Run Code Online (Sandbox Code Playgroud)

and I end up having 9 classes on the QtGui line. There's a third option, which is:

from PyQt4 import QtCore, QtGui
Run Code Online (Sandbox Code Playgroud)

and then prefix all the classes with QtCore or QtGui whenever I use them.

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?

Ale*_*lli 49

你问题标题的答案是"是":我建议永远不要使用from ... import *,我在另一个最近的答案中讨论了原因.简而言之,合格的名称是好的,姓名非常有限,因此"第三选项"是最佳的(因为您将使用合格的名称,而不是姓名).

(合格名称的优点,包括伪名称,包括易于伪造/模拟以用于测试目的,减少因无意识重新绑定引起的未注意错误的无效风险,能够在"跟踪类"中"半假"顶级名称以进行日志记录正是你正在使用和简化诸如剖析之类的活动等等 - 缺点,几乎没有...在禅宗的Python中,import this在交互式解释器提示中也可以看到最后但并非最不重要的公案.

同样好的,如果你吝啬7个额外的字符说QtCore.whatever,是缩写 - from PyQt4 import QtCore as Crfrom PyQt4 import QtGi as Gu(然后使用Cr.blahGu.zorp)等.像所有的缩写,它的简洁和清晰之间的折衷风格(你宁愿名的变量count_of_all_widgets_in_the_inventory,num_widgets或者x?往往是中间的选择是最好的,但并不总是;-).

顺便说一句,我不会as在单个fromimport语句中使用多个子句(可能会令人困惑),我宁愿有多个语句(如果任何导入问题也更容易调试,如果你将来更改导入则编辑) ,...).

  • 在我看来,这个答案对于一种特殊情况已经过时了:最好在“ __init__.py”文件中使用通配符导入来从定义“ __all__”的模块中导入。 (3认同)

Tom*_*cki 14

也有好的案例import *.即.Django开发人员常常有很多配置文件并使用import*链接它们:

settings.py:
FOO = 1
BAR = 2
DEBUG = False

test_settings.py:
from settings import *
DEBUG = True
Run Code Online (Sandbox Code Playgroud)

在这种情况下,大多数缺点import *成为优点.

  • @Phlip同意,但这篇文章的标题是"应该避免使用通配符吗?" 不是"在PyQt4**中应该避免使用通配符**吗?" (7认同)