How Does 'import *' Actually Work in Python?

DDD
Release: 2024-11-16 14:45:03
Original
729 people have browsed it

How Does

Unraveling the "import *" Enigma

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
Copy after login

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
Copy after login

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
Copy after login

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:

  • All names listed in the module's "__all__" variable (if defined).
  • All names except those starting with an underscore ("_"), unless the "__all__" variable is defined.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template