What Does "import *" Import?
In Python, "import *" imports everything from the specified module into the current module. This allows direct access to the imported objects without prefixing them with the module name.
For example:
>>> from math import * >>> pi 3.141592653589793 >>> sin(pi/2) 1.0
Caught in the Web of Name Collisions
However, importing "everything" with "*" is not recommended as it can create namespace collisions with existing variables or functions. Additionally, it may be inefficient if a significant number of objects are imported.
Explicitly Importing vs. Importing with "*"
It is preferable to explicitly import only the necessary objects:
>>> from math import pi >>> pi 3.141592653589793 >>> sin(pi/2) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sin' is not defined
Alternatively, the module can be imported under its own namespace or alias:
>>> import math >>> math.pi 3.141592653589793 >>> import math as m >>> m.pi 3.141592653589793
Exceptions to the "* Import"
In certain cases, it may be appropriate to import everything with "". For instance, some libraries provide sub-modules specifically designed to be imported with "" and contain commonly used constants and functions.
Delving into the "* Import" Mechanism
With "import *", the following objects are imported:
Subtlety of Sub-modules
Contrary to common perception, "from xyz import " does not import sub-modules. Sub-modules must be explicitly imported separately, e.g. "from urllib.request import ".
The above is the detailed content of How Does 'import *' Actually Work in Python?. For more information, please follow other related articles on the PHP Chinese website!