How to write __init__ file in Python

Published on Aug. 22, 2023, 12:16 p.m.

The __init__.py file is used to mark a directory as a Python package, and it can also contain code that will be executed when the package is imported. Here is an example of how to write an __init__.py file:

# This is an example __init__.py file for a Python package.

# Import any modules you want to make available in the package.
from . import module1
from . import module2

# Define any variables or constants you want to make available in the package.
MY_CONSTANT = 42

# Define any functions or classes you want to make available in the package.
def my_function():
    print("Hello, world!")

class MyClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}!")

You can put any Python code you like in the __init__.py file, and it will be executed when the package is imported. It’s common to use __init__.py to import the modules in the package and define any global variables or functions that you want to be available to users of the package. Note that it’s also possible to import other packages or modules within __init__.py and to define sub-packages within your package.

Tags:

related content