Avoidance of Wildcard Imports: Common Practices and Considerations
Despite the warnings raised by linters such as PyLint concerning unused imports, it is generally advised to avoid wildcard imports (from ... import *) due to several reasons.
Prioritizing Qualified Names
Importing modules with qualified names (from PyQt4.QtCore import Qt, QPointF, QRectF) ensures the explicit specification of the required classes, reducing the risk of accidental rebinding or unnoticed errors due to name collisions. Qualified imports also facilitate mocking and tracing during testing and debugging.
Advantages of Abbreviated Imports
While using qualified imports guarantees clarity, it can be tedious to type multiple prefixes. As an alternative, abbreviated imports can be employed, such as from PyQt4 import QtCore as Cr and from PyQt4 import QtGui as Gu. This approach balances conciseness and readability, though it requires careful consideration of abbreviation choices.
Multiple Import Statements
It is preferable to use multiple import statements rather than combining all imports into a single line. This practice enhances readability, simplifies debugging, and allows for easier editing in the future.
Specific Example
In the case presented, the third option (from PyQt4 import QtCore, QtGui) is recommended as it avoids wildcard imports while requiring minimal extra characters compared to the第二 option (explicitly listing multiple classes).
The above is the detailed content of Why Avoid Wildcard Imports in Python?. For more information, please follow other related articles on the PHP Chinese website!