init.py__init__.py
: It is a pythonPython file found in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, i.e. whenever the package is imported the python statements are executed first before the other modules in this folder gets executed. It is similar to main function of c or javaJava program, but this exists in the pythonPython package module (folder) rather than in the core pythonPython file.
also it has access to global variables defined in this init.py__init__.py
file as when the module is imported into pythonPython file.
for eg.
I have a init.py__init__.py
file in a folder called pymodlibpymodlib
, this file contains the following statements:
print(f'Invoking init.py for {name}') pystructures = ['for_loop', 'while__loop', 'ifCondition']
print(f'Invoking __init__.py for {__name__}')
pystructures = ['for_loop', 'while__loop', 'ifCondition']
whenWhen I import this package "pymodlib"pymodlib
in the my solution module or notebook or python console:
thisThese two statements getsget executed while importing.
So in the log or console you would see the following output:
import pymodlib Invoking init.py for pymodlib
>>> import pymodlib
Invoking __init__.py for pymodlib
in the next statement of python console: I can access the global variable:
pymodlib.pystructures it gives the following output:
>> pymodlib.pystructures
['for_loop', 'while__loop', 'ifCondition']it gives the following output:
['for_loop', 'while__loop', 'ifCondition']
Now, from python3Python 3.3 onwards the use of this file has been optional to make folder a pythonPython module. So you can skip from including it in the python module folder.