Net-informations.com
SiteMap  | About    

What is __init__.py for?

Python provides a very straightforward packaging system , which is simply an extension of the module mechanism to a directory. Any directory with an __init__.py file is considered a Python package. The different modules in the package are imported in a similar manner as plain modules, but with a special behaviour for the __init__.py file, which is used to gather all package-wide definitions.

The following image shows the structure of a standard Python module.

What is __init__.py for

As you can see the structure of a standard Python module from the above image, the inclusion of the __init__.py file in a directory indicates to the Python interpreter that the directory should be treated like a Python package. When a module is imported into a script, that module's __init__.py file will be sourced and executed. It provides an easy way for you to group large folders of many separate python scripts into a single importable module.

If you have the files:

and mysock is on your Python path , you can import the code in chat.py as

or

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. Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.