Table of contents

Modules and Packages

Modules and packages in Python allow you to organize your code efficiently, making it more modular, reusable, and maintainable. This guide will cover the basics of creating and using modules and packages, with detailed examples to help you understand their usage and capabilities.

A module is a single file containing Python definitions and statements. Modules allow you to logically organize your Python code, making it easier to manage and reuse.

To create a module, simply save your Python code in a file with a .py extension.

Example: mymodule.py

# mymodule.py def greet(name): return f"Hello, {name}!" def add(a, b): return a + b

You can import a module using the import statement. Once imported, you can access the functions and variables defined in the module using the dot notation.

Example: Using mymodule

# main.py import mymodule print(mymodule.greet("Alice")) # Output: Hello, Alice! print(mymodule.add(3, 5)) # Output: 8

You can import specific functions or variables from a module using the from keyword.

Example

# main.py from mymodule import greet, add print(greet("Bob")) # Output: Hello, Bob! print(add(10, 20)) # Output: 30

You can use aliases to give a module or function a different name when importing.

Example

# main.py import mymodule as mm from mymodule import greet as hello print(mm.add(5, 7)) # Output: 12 print(hello("Charlie")) # Output: Hello, Charlie!

Python comes with a rich standard library, which is a collection of modules and packages that provide many useful functionalities. You can import these modules just like any other module.

Example: Using math Module

import math print(math.sqrt(16)) # Output: 4.0 print(math.pi) # Output: 3.141592653589793

Example: Using datetime Module

import datetime now = datetime.datetime.now() print(now) # Output: Current date and time date_str = "2023-01-01" date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d") print(date_obj) # Output: 2023-01-01 00:00:00

A package is a way of organizing related modules into a directory hierarchy. A package is a directory containing an __init__.py file and one or more module files.

Directory Structure

mypackage/ __init__.py module1.py module2.py

Example: mypackage/module1.py

# mypackage/module1.py def function1(): return "Function 1 from module 1"

Example: mypackage/module2.py

# mypackage/module2.py def function2(): return "Function 2 from module 2"

You can import modules from a package using the dot notation.

Example: Using mypackage

# main.py from mypackage import module1, module2 print(module1.function1()) # Output: Function 1 from module 1 print(module2.function2()) # Output: Function 2 from module 2

The __init__.py file makes Python treat the directory as a package. It can be empty or execute initialization code for the package.

Example: mypackage/__init__.py

# mypackage/__init__.py from .module1 import function1 from .module2 import function2

Example: Using mypackage with __init__.py

# main.py from mypackage import function1, function2 print(function1()) # Output: Function 1 from module 1 print(function2()) # Output: Function 2 from module 2

Packages can be nested within other packages. You can import modules from nested packages using the dot notation.

Example: Nested Packages

Directory Structure

mypackage/ __init__.py subpackage/ __init__.py module3.py

Example: mypackage/subpackage/module3.py

# mypackage/subpackage/module3.py def function3(): return "Function 3 from module 3"

Example: Using Nested Packages

# main.py from mypackage.subpackage import module3 print(module3.function3()) # Output: Function 3 from module 3

Let’s build a simple calculator package that can perform basic arithmetic operations.

Directory Structure

calculator/ __init__.py add.py subtract.py multiply.py divide.py

Example: calculator/add.py

# calculator/add.py def add(a, b): return a + b

Example: calculator/subtract.py

# calculator/subtract.py def subtract(a, b): return a - b

Example: calculator/multiply.py

# calculator/multiply.py def multiply(a, b): return a * b

Example: calculator/divide.py

# calculator/divide.py def divide(a, b): if b != 0: return a / b else: return "Error: Division by zero"

Example: calculator/__init__.py

# calculator/__init__.py from .add import add from .subtract import subtract from .multiply import multiply from .divide import divide

Example: Using the Calculator Package

# main.py from calculator import add, subtract, multiply, divide print(add(5, 3)) # Output: 8 print(subtract(10, 4)) # Output: 6 print(multiply(6, 7)) # Output: 42 print(divide(8, 2)) # Output: 4.0 print(divide(5, 0)) # Output: Error: Division by zero

Create a package mathutils with modules for common mathematical operations like factorial, power, and square root.

Directory Structure

mathutils/ __init__.py factorial.py power.py sqrt.py

Example: mathutils/factorial.py

# mathutils/factorial.py def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)

Example: mathutils/power.py

# mathutils/power.py def power(base, exp): return base ** exp

Example: mathutils/sqrt.py

# mathutils/sqrt.py def sqrt(x): return x ** 0.5

Example: mathutils/__init__.py

# mathutils/__init__.py from .factorial import factorial from .power import power from .sqrt import sqrt

Example: Using the mathutils Package

# main.py from mathutils import factorial, power, sqrt print(factorial(5)) # Output: 120 print(power(2, 3)) # Output: 8 print(sqrt(16)) # Output: 4.0

Create a package stringutils with modules for string manipulation operations like reversing a string, converting to uppercase, and counting vowels.

Create a package fileutils with modules for file operations like reading a file, writing to a file, and appending to a file.

In this guide, we’ve explored Python modules and packages, including creating and using modules, the standard library, creating packages, and importing from nested packages. Modules and packages are essential for organizing and reusing code efficiently. Practice these concepts with the provided examples and exercises to enhance your understanding and programming skills. In the next section, we will delve into file handling, which is crucial for working with data stored in files. Happy coding!