Python Modules and Packages
What is a Module in Python?
A Python module is simply a .py file that contains Python definitions, functions, classes, or variables which can be reused in other Python programs using the import statement.
Example: Creating a Python Module
Let's say you create a file named mymodule.py:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
Now, in another Python file, you can use this module:
# main.py
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.PI) # Output: 3.14159
Explanation:
- You've just reused code via a Python module!
Types of Imports in Python
Python allows you to import modules in multiple ways:
import math
from math import sqrt
from math import pi as PI
import mymodule as mm
Import Styles:
- import module - Full module import
- from module import item - Direct import of specific item
- import module as alias - Import with alias
What is a Package in Python?
A Python package is a directory that contains a collection of modules and a special __init__.py file (can be empty) that tells Python the directory is a package.
Example: Creating a Python Package
Directory structure:
myapp/
│
├── mypackage/
│ ├── __init__.py
│ ├── math_utils.py
│ └── string_utils.py
└── main.py
math_utils.py:
def add(x, y):
return x + y
string_utils.py:
def shout(text):
return text.upper()
main.py:
from mypackage.math_utils import add
from mypackage.string_utils import shout
print(add(5, 3)) # 8
print(shout("hello")) # HELLO
The Role of __init__.py File
The __init__.py file marks a directory as a Python package and initializes it. It can be:
- Empty - just marks the package
- Functional - can import submodules or define package-level variables
# mypackage/__init__.py
from .math_utils import add
Now you can do:
from mypackage import add
print(add(2, 3)) # Output: 5
Built-in vs Custom Modules
- Built-in: math, os, sys
- Third-party: requests, numpy
- User-defined: Custom .py files
Example: Using Built-in Module
import os
print(os.getcwd()) # Get current working directory
print(os.listdir(".")) # List files in current directory
Installing Third-Party Packages (Using pip)
pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
Organizing Code with Modules and Packages
- Split logic into multiple modules for readability
- Group related modules into packages
- Use __init__.py to control package exposure
- Keep your project scalable and maintainable
Absolute vs Relative Import in Python Packages
- Absolute Import: from mypackage.module import x - For top-level clarity
- Relative Import: from .module import x - For internal package references