Should wildcard import be avoided?

Viewed 53756

I'm using PyQt and am running into this issue. If my import statements are:

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:

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:

from PyQt4 import QtCore, QtGui

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?

6 Answers

I am too absolutely against import * in the general case. In the case of PySide2, one of the rare exceptions applies:

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 CMAKE generator. Very helpful when quickly trying something in the interactive console, but also in automated testing.

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.

Related