60 lines
1.9 KiB
Plaintext
60 lines
1.9 KiB
Plaintext
Importing every public name from a module using a wildcard (``++from mymodule import *++``) is a bad idea because:
|
|
|
|
* It could lead to conflicts between names defined locally and the ones imported.
|
|
* It reduces code readability as developers will have a hard time knowing where names come from.
|
|
* It clutters the local namespace, which makes debugging more difficult.
|
|
|
|
Remember that imported names can change when you update your dependencies. A wildcard import which works today might be broken tomorrow.
|
|
|
|
|
|
There are two ways to avoid a wildcard import:
|
|
|
|
* Replace it with ``++import mymodule++`` and access module members as ``++mymodule.myfunction++``. If the module name is too long, alias it to a shorter name. Example: ``++import pandas as pd++``
|
|
* List every imported name. If necessary import statements can be split on multiple lines using parentheses (preferred solution) or backslashes.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
from math import * # Noncompliant
|
|
def exp(x):
|
|
pass
|
|
print(exp(0)) # "None" will be printed
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
import math
|
|
def exp(x):
|
|
pass
|
|
print(math.exp(0)) # "1.0" will be printed
|
|
----
|
|
Or
|
|
|
|
----
|
|
from math import exp as m_exp
|
|
def exp(x):
|
|
pass
|
|
print(m_exp(0)) # "1.0" will be printed
|
|
----
|
|
|
|
== Exceptions
|
|
|
|
No issue will be raised in ``++__init__.py++`` files. Wildcard imports are a common way of populating these modules.
|
|
|
|
No issue will be raised in modules doing only imports. Local modules are sometimes created as a proxy for third-party modules.
|
|
|
|
----
|
|
# file: mylibrary/pyplot.py
|
|
try:
|
|
from guiqwt.pyplot import * # Ok
|
|
except Exception:
|
|
from matplotlib.pyplot import * # Ok
|
|
----
|
|
|
|
Just keep in mind that wildcard imports might still create issues in these cases. It's always better to import only what you need.
|
|
|
|
== See
|
|
|
|
* https://docs.python.org/3.8/reference/simple_stmts.html#import[Python documentation - The import statement]
|