Learn how to organize Python code using modules and packages, import statements, and create reusable code libraries.
Python modules and packages are essential for organizing code into reusable, maintainable components. This lesson covers how to create, import, and organize Python code effectively using modules and packages.
Modern software development relies heavily on modular design principles. By breaking code into logical modules and packages, you create systems that are easier to test, maintain, and scale. Companies like Google, Netflix, and Microsoft use sophisticated module architectures to manage millions of lines of code efficiently.
In this lesson, you'll learn professional-grade techniques for organizing Python code, from simple modules to complex package hierarchies, giving you the skills to build enterprise-level applications.
A module in Python is simply a file containing Python code. Any Python file can be imported as a module, allowing you to organize related functions, classes, and variables together.
Creating a Basic Module:
1# math_operations.py
2def add(a, b):
3 """Add two numbers"""
4 return a + b
5
6def multiply(a, b):
7 """Multiply two numbers"""
8 return a * b
9
10PI = 3.14159Using the Module:
1# main.py
2import math_operations
3
4result = math_operations.add(5, 3)
5print(f"5 + 3 = {result}")
6print(f"PI value: {math_operations.PI}")Modules promote code reusability and maintainability by allowing you to break large programs into smaller, manageable files.
Python provides several ways to import modules, each with specific use cases and best practices.
Different Import Methods:
1# Method 1: Import entire module
2import math_operations
3result = math_operations.add(5, 3)
4
5# Method 2: Import specific functions
6from math_operations import add, multiply
7result = add(5, 3)
8
9# Method 3: Import with alias
10import math_operations as math_ops
11result = math_ops.add(5, 3)
12
13# Method 4: Import all (generally discouraged)
14from math_operations import *
15result = add(5, 3)Best Practices:
from module import functionimport very_long_module_name as vlmnimport * to prevent namespace pollutionPackages are directories containing multiple modules with a special __init__.py file. They allow you to organize related modules together and create hierarchical namespaces.
Package Structure:
1my_package/
2 __init__.py
3 module1.py
4 module2.py
5 subpackage/
6 __init__.py
7 submodule.pyCreating a Package:
1# my_package/__init__.py
2from .module1 import function1
3from .module2 import function2
4
5__version__ = "1.0.0"
6__all__ = ["function1", "function2"]
7
8# my_package/module1.py
9def function1():
10 return "Hello from module1"
11
12# Using the package
13import my_package
14result = my_package.function1()Packages create tree-like structures that make large codebases manageable and logical, enabling teams to work on different components independently.
Python comes with an extensive standard library containing modules for common tasks, saving development time and ensuring reliable, tested code.
Essential Standard Library Modules:
1# Operating system interface
2import os
3current_dir = os.getcwd()
4os.path.join("path", "to", "file")
5
6# Date and time handling
7import datetime
8now = datetime.datetime.now()
9formatted = now.strftime("%Y-%m-%d %H:%M:%S")
10
11# JSON processing
12import json
13data = {"name": "John", "age": 30}
14json_string = json.dumps(data)
15parsed_data = json.loads(json_string)
16
17# Random number generation
18import random
19random_int = random.randint(1, 100)
20random_choice = random.choice(["a", "b", "c"])
21
22# Mathematical functions
23import math
24sqrt_result = math.sqrt(16)
25pi_value = math.piCategories of Standard Library:
Your progress is saved in this browser, on this device only.