Initializing a package
To initialize a package, you place the Python code inside the package's __init__.py
file. This code is then executed when the package is imported. For example, imagine that you have a package named test_package
, which contains an __init__.py
file and one module named test_module.py
:
You can place whatever code you like inside the __init__.py
file, and when the package (or a module within the package) is imported for the first time, that code will be executed.
You might be wondering why you might want to do this. Initializing a module makes sense as a module contains various functions that might need to be initialized before they are used (for example, by setting global variables to an initial value). But why initialize a package, rather than just a module within that package?
The answer lies in what happens when you import a package. When you do this, anything you define in the package's __init__.py
file becomes available at the package level. For example, imagine that...