Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is __init__.py for?

What is __init__.py for in a Python source directory?

like image 394
Mat Avatar asked Jan 15 '09 20:01

Mat


People also ask

What is purpose of __ init __ py?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

What is __ init __ .py in Python?

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

Is __ init __ py necessary?

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

What is the purpose of init py in project dictionary?

The __init__.py file lets the Python interpreter know that a directory contains code for a Python module. An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project.


2 Answers

It used to be a required part of a package (old, pre-3.3 "regular package", not newer 3.3+ "namespace package").

Here's the documentation.

Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.

But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py.

like image 149
Loki Avatar answered Sep 28 '22 03:09

Loki


Files named __init__.py are used to mark directories on disk as Python package directories. If you have the files

mydir/spam/__init__.py mydir/spam/module.py 

and mydir is on your path, you can import the code in module.py as

import spam.module 

or

from spam import module 

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

import spam 

based on this

like image 43
caritos Avatar answered Sep 28 '22 03:09

caritos