Home > Backend Development > Python Tutorial > Does 'import *' Import __init__.py in Python?

Does 'import *' Import __init__.py in Python?

Linda Hamilton
Release: 2024-12-10 08:10:10
Original
1061 people have browsed it

Does

What Does "import *" Import in Python and How Does It Relate to __init__.py?

In Python, the "import *" statement imports all non-private (i.e., not starting with an underscore) symbols from a specified module into the current module. This allows direct access to the imported symbols without using the module name prefix.

Does "import *" Import __init__.py?

No, the "import *" statement does not automatically import the __init__.py file found in the containing folder. __init__.py is a special file that Python uses to initialize a module when it is imported. To explicitly import __init__.py, you must use the "import" statement with the module name as follows:

Advantages and Disadvantages of "import *":

The main advantage of "import *" is the convenience of importing all symbols at once. However, this practice is generally discouraged due to:

  • Namespace collisions: Imported symbols may conflict with existing symbols in the current module.
  • Inefficiency: Importing a large number of symbols may slow down the program.
  • Lack of explicit documentation: It can be difficult to track the origin of imported symbols when using "*".

Preferred Practices:

Instead of "import *", it is recommended to import only the specific symbols you need. This can be done using either:

  • Explicit import:

  • Module aliasing:

Submodules and "import *":

When a module contains submodules, "import *" does not import these submodules unless they are explicitly included in the all attribute of the main module.

Conclusion:

While "import *" can be convenient, it is generally discouraged in favor of explicit imports or module aliasing. __init__.py is a special file used to initialize a module, and it must be imported separately using the "import" statement.

The above is the detailed content of Does 'import *' Import __init__.py 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