What Is __Init__.Py File in Python? |
Python allows users to organize their code into modules and packages which are collections of modules the __init__.py file is a Python file that is executed when a package is imported __init__.py is a special file used in Python to define packages and initialize their namespaces file can contain an initialization code that runs when the package is imported without this file Python won't recognize a directory as a package file serves two main purposes
|
Syntax of Importing __Init__.py File |
two ways to import a package
# import the module import <package_name>.<module_name> # import specific functions, classes or variables from <package_name>.<module_name> import <object>avoid using the '*' operator to import all names from a package/module it may lead to conflicts and reduce code readability from <package_name>.<module_name> import * |
Creating a Simple Package Using __init__.py File |
create a directory named 'mypackage' in directory add the modules
the File structure should appear as mypackage __init__.py module1.py module2.py main.py__init__.py is an empty file module1.py code # Define a function called func1 def func1(): print("This is func1 from module1")module2.py code # Define a function called func2 def func2(): print("This is func2 from module2")below the __all__ variable is a list of strings that indicate the names that should be imported when using the * operator the dot operator (.) before the module names means that they are relative imports (imported from the same package) # Define the __all__ variable __all__ = ["module1", "module2"] # Import the submodules from . import module1 from . import module2main.py is the 'mule' # Import the package import mypackage # Import the modules import mypackage.module1 import mypackage.module2 # Call the functions mypackage.module1.func1() mypackage.module2.func2() |
Package Import Optimization Using __init__.py File |
a better main.py
# main.py # Import specific modules instead of using * from mypackage import module1, module2 # Call the functions module1.func1() module2.func2() |
Define Variables and Execute Code in __init__.py file |
if there is a need to initialize variables or execute code when a package is imported,
it can be done in the __init__.py file below the welcome message is printed whae the module is imported # Define a variable called version version = "1.0.0" # Print a welcome message print(f"Welcome to mypackage version {version}") |