Wildcard imports, such as from PyQt4 import *, are a common source of debate in the programming community. However, many developers agree that they should generally be avoided.
Qualified names are preferred over barenames. It's better to explicitly specify the module from which you're importing, using syntax like from PyQt4.QtCore import Qt rather than from PyQt4 import Qt. Qualified names make it easier to trace code dependencies and debug errors.
They also reduce the risk of collisions between modules. If two modules define a function with the same name, you need to explicitly import one of them to avoid ambiguity. Wildcard imports make it easier to overlook such collisions, leading to unexpected errors.
Finally, wildcard imports can make it harder to test your code. For example, if you're mocking a class from a third-party library, it's easier to do so if you have a qualified reference to the class.
If you want to reduce the number of lines in your import statements, you can create aliases for modules. For example, instead of writing from PyQt4.QtCore import Qt, QPointF, QRectF, you could write:
import PyQt4 Qt = PyQt4.QtCore
This approach allows you to use Qt.QPointF, Qt.QRectF, etc. without having to explicitly qualify each name.
Another option is to use selective importing. Instead of importing all classes from a module, you can import only the ones you need:
from PyQt4.QtCore import QPointF, QRectF from PyQt4.QtGui import QGraphicsItem, QGraphicsScene
This is more verbose than using a wildcard import, but it has the advantage of only importing the classes you actually use.
Although wildcard imports can be tempting, they are generally not recommended. Qualified names are more readable, less error-prone, and easier to test. If you're looking for ways to reduce the number of lines in your import statements, consider using aliases or selective importing instead.
The above is the detailed content of Wildcard Imports: To Use or Not to Use?. For more information, please follow other related articles on the PHP Chinese website!