Python Modules

Learn how to create, import, and use modules in Python to organize and reuse your code.

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example - Save this code in a file named mymodule.py:

def greeting(name):
    print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example - Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example - Save this code in the file mymodule.py:

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Example - Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example - Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example - Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

Example - List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example - The module named mymodule has one function and one dictionary:

def greeting(name):
    print("Hello, " + name)

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Example - Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"]

Import All

You can import all names from a module by using the * wildcard:

Example - Import all names from mymodule:

from mymodule import *

greeting("Jonathan")
print(person1["age"])

Note: It's generally not recommended to use import * as it can lead to namespace pollution.

Module Search Path

Python looks for modules in several locations:

Example - Check the module search path:

import sys

for path in sys.path:
    print(path)
  • Current directory
  • PYTHONPATH environment variable directories
  • Standard library directories
  • Site-packages directory

Creating Packages

A package is a collection of modules in directories that give structure to your code:

Example - Package structure:

mypackage/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        module3.py

Example - __init__.py file:

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

__all__ = ['function1', 'function2']

Example - Using the package:

import mypackage
from mypackage import module1
from mypackage.subpackage import module3

# Use functions
mypackage.function1()
module1.function1()
module3.some_function()

Module Documentation

Good modules should include documentation:

Example - Well-documented module:

"""
Math utilities module.

This module provides various mathematical utility functions
for common calculations.
"""

import math

def calculate_area_circle(radius):
    """
    Calculate the area of a circle.
    
    Args:
        radius (float): The radius of the circle
        
    Returns:
        float: The area of the circle
        
    Raises:
        ValueError: If radius is negative
    """
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

def calculate_distance(x1, y1, x2, y2):
    """
    Calculate the distance between two points.
    
    Args:
        x1, y1 (float): Coordinates of first point
        x2, y2 (float): Coordinates of second point
        
    Returns:
        float: The distance between the points
    """
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

# Module-level constants
PI = math.pi
E = math.e

Common Built-in Modules

os

Operating system interface

import os
print(os.getcwd())
os.mkdir('new_folder')

sys

System-specific parameters

import sys
print(sys.version)
sys.exit()

datetime

Date and time handling

import datetime
now = datetime.datetime.now()
print(now)

random

Generate random numbers

import random
print(random.randint(1, 10))
print(random.choice(['a', 'b', 'c']))

json

JSON encoder and decoder

import json
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)

urllib

URL handling modules

import urllib.request
response = urllib.request.urlopen('http://example.com')

Best Practices

  • Use descriptive module names
  • Keep modules focused on a single purpose
  • Include docstrings for modules and functions
  • Use if __name__ == "__main__": for executable scripts
  • Avoid circular imports
  • Use relative imports within packages

Example - Module with main guard:

"""Calculator module with basic operations."""

def add(a, b):
    """Add two numbers."""
    return a + b

def subtract(a, b):
    """Subtract two numbers."""
    return a - b

def main():
    """Main function for testing."""
    print("Testing calculator module")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"5 - 3 = {subtract(5, 3)}")

if __name__ == "__main__":
    main()