Organizing and Reusing Code
.py file is a moduleBenefits:
Example Structure:
my_project/
├── main.py
├── utils/
│ ├── math_utils.py
│ ├── string_utils.py
│ └── file_utils.py
└── models/
├── user.py
└── product.py
Import specific functions:
Import everything (use with caution):
Import with custom names:
Common built-in modules:
Create a module file: calculator.py
"""A simple calculator module."""
def add(a, b):
"""Add two numbers."""
return a + b
def subtract(a, b):
"""Subtract second number from first."""
return a - b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
def divide(a, b):
"""Divide first number by second."""
if b != 0:
return a / b
else:
raise ValueError("Cannot divide by zero!")
# Module-level variable
VERSION = "1.0.0"In another file: main.py
Python looks for modules in this order:
Packages are directories containing multiple modules:
my_package/
├── __init__.py # Makes it a package
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py
The __init__.py file: - Makes a directory a Python package - Can be empty or contain initialization code - Controls what gets imported with from package import *
Directory structure:
math_tools/
├── __init__.py
├── basic.py
└── advanced.py
math_tools/__init__.py:
Import from package:
# Import entire package
import math_tools
result = math_tools.add(5, 3)
# Import specific modules
from math_tools import basic
result = basic.add(5, 3)
# Import specific functions
from math_tools.basic import add
result = add(5, 3)
# Import from package root (if defined in __init__.py)
from math_tools import add
result = add(5, 3)Absolute imports (from project root):
__name__ VariableEvery module has a __name__ attribute:
When imported: __name__ is the module name When run directly: __name__ is "__main__"
Good module documentation:
"""
utils.py - Utility functions for data processing
This module provides common utility functions for:
- String manipulation
- File operations
- Data validation
Example:
>>> from utils import clean_string
>>> clean_string(" Hello World ")
'Hello World'
"""
def clean_string(text):
"""
Remove leading/trailing whitespace and normalize.
Args:
text (str): The string to clean
Returns:
str: Cleaned string
"""
return text.strip()Why use virtual environments? - Isolate project dependencies - Avoid version conflicts - Keep global Python clean
Requirements file:
Example requirements.txt:
requests==2.28.1
numpy==1.21.0
pandas>=1.3.0
matplotlib~=3.5.0
Package structure:
file_utils/
├── __init__.py
├── readers.py
└── writers.py
file_utils/readers.py:
Challenge 1: Create a String Utils Module
Challenge 2: Create a Simple Package
helpers/
├── __init__.py
├── math_helpers.py
└── string_helpers.py
String Utils Module:
database_utils not db_stuff__init__.py: Control package imports1. Circular imports:
2. Modifying sys.path incorrectly:
For development/debugging:
Note: Reloading has limitations and should mainly be used during development
import statements to access module functionalityComing up next: - Object-oriented programming concepts - Classes and inheritance - Advanced Python features
Practice more: - Create a utilities package for your common tasks - Explore the Python standard library - Build a simple project with multiple modules
Python Tutorial