Home » Learn Python » Modules and Packages » Package Initialisation

Package Initialisation

A package in Python is just a directory, which can contain modules (Python files with a .py extension).

If you place a file called __init__.py in the directory, it will run when you import the package.

mystuff/__init__.py
print("Package initialisation running")
myprog.py
import mystuff as mm
output:
Package initialisation running

Importing Packages Directly

Instead of importing particular module files from packages, if you place an __init__.py in the package directory, you can place variables, functions and other code directly in __init__.py. Then you can use them by importing the package.

So, instead of importing a .py module, you import the directory (package), which loads __init__.py

Even if you don’t intend to use __init__.py, it’s a good idea to add one to every directory within a package, to flag the directory as being a package.

mystuff/__init__.py
PI = 3.141592

def greet():
    print("Hello")
myprog.py
import mystuff as mm

print(mm.PI)

mm.greet()
output:
3.141592
Hello

Leave a Reply

Blog at WordPress.com.

%d