Modules
Organize code across files and import functions, classes, and packages
Overview
A module is a .py file; a package is a directory with __init__.py. The import system lets you reuse code, access the standard library, and install third-party packages with pip.
Syntax / Usage
# Import entire module
import math
math.sqrt(16) # 4.0
# Import specific names
from datetime import datetime, timedelta
# Alias
import numpy as np
# Relative imports (inside packages)
from .utils import helper
from ..models import User
# __name__ guard for script vs module
if __name__ == "__main__":
main()
Project layout example:
myapp/
__init__.py
models.py
services/
__init__.py
auth.py
Examples
Create a reusable utility module string_utils.py:
def slugify(text: str) -> str:
return text.lower().strip().replace(" ", "-")
Use it elsewhere:
from string_utils import slugify
slugify("Hello World") # "hello-world"
Install and use a third-party package:
pip install requests
import requests
response = requests.get("https://api.github.com")
data = response.json()
Common Mistakes
- Circular imports between modules—restructure or use lazy imports
- Using
from module import *and polluting the namespace - Running scripts from the wrong working directory, breaking imports
- Naming your file
json.pyand shadowing the standard library
See Also
python-functions python-file-io python-classes