What is __Init__.Py File in Python?
Last Updated : 19 Mar, 2024
One of the features of Python is that it 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. In this article, we will see what is __init__.py file in Python and how it is used in Python.
What Is __Init__.Py File in Python?
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. It can contain an initialization code that runs when the package is imported. Without this file, Python won't recognize a directory as a package. It serves two main purposes:
- It marks the directory as a Python Package so that the interpreter can find the modules inside it.
- It can contain initialization code for the Package, such as importing submodules, defining variables, or executing other code.
Syntax of Importing and Using __Init__.py File
To import a package or module, use the 'import' keyword followed by the package or module name. For instance, importing module1 from the 'package' package is done with:
import mypackage.module1
Alternatively, use 'from' followed by the package/module name, and 'import' for specific functions, classes, or variables. Example:
from mypackage.module1 import func1
Avoid using the '*' operator to import all names from a package/module, as it may lead to conflicts and reduce code readability. For instance:
from mypackage import *
Note that this method only imports names defined in the init.py file, excluding submodules. To include submodules, use all variables in init.py to specify the modules or names to import.
Usage of __Init__.py File in Python
Below are some of the example of __Init__.Py File uses in Python:
- Creating a Simple Package Using __init__.py File
- Package Import Optimization Using __init__.py File
- Define Variable and Execute Code in __init__.py file
Creating a Simple Package Using __init__.py File
Create a directory named 'mypackage' with two modules inside: 'module1.py' containing 'func1' and 'module2.py' containing 'func2'. To make it a Python package, include an empty 'init.py' file in the 'mypackage' directory. The File structure should appear as follows:
File Structure

__init__.py :In below code, the __all__ variable is a list of strings that indicate the names that should be imported when using the * operator. The dot (.) before the module names means that they are relative imports, which means that they are imported from the same package.
Python3 # Define the __all__ variable __all__ = ["module1", "module2"] # Import the submodules from . import module1 from . import module2
module1.py : Define a function named "func1" in Python, which prints "This is func1 from module1" when called.
Python3 # Define a function called func1 def func1(): print("This is func1 from module1")
module2.py : Define a function named "func2" in Python, which prints "This is func2 from module2" when called.
Python3 # Define a function called func2 def func2(): print("This is func2 from module2")
main.py : In below code, a package named "mypackage" is imported, and then two specific modules, "module1" and "module2," within that package are imported. Finally, functions from each module, namely "func1" from "module1" and "func2" from "module2," are called.
Python3 # Import the package import mypackage # Import the modules import mypackage.module1 import mypackage.module2 # Call the functions mypackage.module1.func1() mypackage.module2.func2()
Output
This is func1 from module1 This is func2 from module2
Package Import Optimization Using __init__.py File
Imagine we intend to utilize the from package import * syntax to import all modules or names from our package. For instance, we aim to include the following code in main.py:
main.py : In the main.py
file, specific modules (module1
and module2
) are imported from the "mypackage," avoiding the use of the wildcard (*) import
Python # main.py # Import specific modules instead of using * from mypackage import module1, module2 # Call the functions module1.func1() module2.func2()
__init__.py : Below, code defines the __all__ variable to specify which modules or names should be imported when using the wildcard (*) import. Then, it imports the specified submodules (module1 and module2) within the current package using relative import syntax.
Python # Define the __all__ variable __all__ = ["module1", "module2"] # Import the submodules from . import module1 from . import module2
Output
This is func1 from module1 This is func2 from module2
Define Variable and Execute Code in __init__.py file
If there is a need to initialize variables or execute code when a Python package is imported, this can be accomplished in the __init__.py file. For instance, to define a version variable holding the package version and display a welcome message upon import, the following code can be included in the __init__.py file.
__intit__.py : In below code , a variable named "version" is defined with the value "1.0.0," and a welcome message including the package version is printed.
Python3 # Define a variable called version version = "1.0.0" # Print a welcome message print(f"Welcome to mypackage version {version}")
main.py : In below code, the "mypackage" is imported, and the version variable from the package is printed, displaying the version information of the package.
Python3 # Import the package import mypackage # Print the version print(mypackage.version)
Output
Welcome to mypackage version 1.0.0 1.0.0
Similar Reads
File System Manipulation in Python
File system manipulation in Python refers to the ability to perform various operations on files, such as creating, reading, writing, appending, renaming, and deleting. Python provides several built-in modules and functions that allow you to perform various file system operations. Python treats files
3 min read
What Does Super().__Init__(*Args, **Kwargs) Do in Python?
In Python, super().__init__(*args, **kwargs) is like asking the parent class to set itself up before adding specific details in the child class. It ensures that when creating an object of the child class, both the parent and child class attributes are initialized correctly. It's a way of saying, In
4 min read
How to Import Other Python Files?
We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse
3 min read
File Versioning in Python
In Python, the term "file versioning" usually refers to the process of keeping track of several file versions, frequently recording changes, preserving the past, and promoting cooperation in software development projects. In this article, we will what is file versioning in Python and how we can use
3 min read
Create a Log File in Python
Logging is an essential aspect of software development, allowing developers to track and analyze the behavior of their programs. In Python, creating log files is a common practice to capture valuable information during runtime. Log files provide a detailed record of events, errors, and other relevan
3 min read
Pipx : Python CLI package tool
In this article, we will explore the basics of pipx python CLI package tool. Pipx is a tool in Python that allows us to run python packages that have a CLI interface in the global context of your system. It uses its own environment for managing the packages. Here, we will cover its installations, se
4 min read
Python Super() With __Init__() Method
In object-oriented programming, inheritance plays a crucial role in creating a hierarchy of classes. Python, being an object-oriented language, provides a built-in function called super() that allows a child class to refer to its parent class. When it comes to initializing instances of classes, the
4 min read
Install Poetry to Manage Python Dependencies
Poetry is a modern and user-friendly dependency management tool for Python. It simplifies the process of managing project dependencies, packaging, and publishing. In this article, we will see how to install poetry in Python in Windows. What is Python Poetry?Python Poetry is a modern and comprehensiv
2 min read
Defaultdict in Python
In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it. Key Features of defaultdict:When we access a key that doesn
6 min read
Create A File If Not Exists In Python
In Python, creating a file if it does not exist is a common task that can be achieved with simplicity and efficiency. By employing the open() function with the 'x' mode, one can ensure that the file is created only if it does not already exist. This brief guide will explore the concise yet powerful
2 min read