Wildcard Imports: The Question of Avoidance
When working with the PyQt library, developers often encounter the question of whether or not to use wildcard imports. Here, we explore the different options and discuss the technical rationale behind using one approach over another.
One option is to use specific imports for each class or module, as in:
from PyQt4.QtCore import Qt, QPointF, QRectF from PyQt4.QtGui import QGraphicsItem, QGraphicsScene, ...
This results in a more concise import statement but requires prefixing each class with its module name, which can beumbersome.
Another option is to use wildcard imports, as in:
from PyQt4 import QtCore, QtGui
This allows for direct access to classes without prefixes but can lead to hundreds of "Unused import" warnings when using linters such as PyLint.
A third option is to import selectively, using wildcard imports for some modules and specific imports for others:
from PyQt4 import QtGui from PyQt4.QtCore import Qt, QPointF, QRectF
This approach balances conciseness with the ability to suppress "Unused import" warnings.
The preferred practice is to avoid wildcard imports altogether. Qualified names (e.g., QtCore.Qt) are preferable to barenames (e.g., Qt) because they provide greater clarity and flexibility, particularly when testing or debugging.
If using qualified names is undesirable, abbreviations can be considered:
import PyQt4.QtCore as Core import PyQt4.QtGui as UI
However, abbreviations may reduce code readability.
Additionally, it is recommended to use multiple import statements instead of a single import statement with multiple clauses, as this improves clarity and debugging. For example:
import PyQt4.QtCore import PyQt4.QtGui
By avoiding wildcard imports and using qualified names, developers can improve the maintainability and readability of their PyQt code.
以上是PyQt 中的通配符导入:使用还是不使用?的详细内容。更多信息请关注PHP中文网其他相关文章!