Home >Backend Development >Python Tutorial >What Does the `import *` Statement Actually Import in Python?

What Does the `import *` Statement Actually Import in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 06:33:03660browse

What Does the `import *` Statement Actually Import in Python?

What the Import * Statement Imports

In Python, the import * statement imports all objects from the specified module into the current module. This allows the use of exported symbols (variables, classes, methods, etc.) from the imported module without prefixing them with the module name.

Example:

>>> from math import *
>>> pi
3.141592653589793
>>> sin(pi/2)
1.0

Comparison to Explicit Imports:

However, using import * is generally discouraged due to:

  • Namespace collisions: Imported objects can override existing symbols in the current module.
  • Inefficiency: Importing many objects can slow down the program.
  • Lack of documentation: It doesn't explicitly document the origin of imported objects.

Instead, it's better practice to:

  • Import specific objects only: Use from module import object to import only the required objects.
  • Import the module with its namespace: Use import module as alias to access imported objects via the module name or alias.

Exceptions:

Some libraries may have specialized sub-modules designed to be imported with import *. For instance, the Pygame library's pygame.locals sub-module contains commonly used constants and functions.

Importing from Sub-Modules:

Importing from sub-modules requires explicit specification, even when using import * within the sub-module. For example, from urllib import * does not import all sub-modules like urllib.request.

The above is the detailed content of What Does the `import *` Statement Actually Import in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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