Why Avoid Wildcard Imports in Python?

Mary-Kate Olsen
Release: 2024-11-19 05:56:02
Original
974 people have browsed it

Why Avoid Wildcard Imports in Python?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template