What is a 'module' in Python?

A foundational guide to modules in Python. Learn how modules are used to organize code into separate files, making your programs more manageable, reusable, and easier to understand.

As your Python programs grow larger, it's a bad idea to keep all your code in a single file. It quickly becomes long, hard to read, and difficult to maintain. The solution to this is to break your code up into smaller, more manageable pieces. In Python, the way we do this is with modules.

A module is simply a file containing Python code. A module can define functions, classes, and variables. It can also include runnable code. By grouping related code into a module, you can make your programs more organized and reusable.

Creating a Module

Creating a module is as simple as creating a Python file. Let's create a module for some greeting functions. We'll save this code in a file named greetings.py.

# greetings.py

"""A module for various greeting functions."""

def say_hello(name):
    return f"Hello, {name}!"

def say_goodbye(name):
    return f"Goodbye, {name}!"

We now have a module named greetings.

Using a Module: The import Statement

To use the functions from our greetings module in another file, we need to import it. Let's create a main.py file in the same directory.

There are several ways to use the import statement.

1. Import the Entire Module

This is the most common and recommended way. You import the module and then access its members using dot notation (module_name.function_name).

# main.py

import greetings

message1 = greetings.say_hello("Alice")
message2 = greetings.say_goodbye("Alice")

print(message1)
print(message2)

This is clear and explicit. It's obvious that say_hello is coming from the greetings module, which avoids naming conflicts.

2. Import Specific Members

You can also import specific functions or classes from a module directly into the current namespace using the from ... import ... syntax.

# main.py

from greetings import say_hello

# Now you can call the function directly
message = say_hello("Bob")
print(message)

This can make your code more concise, but it can also lead to naming conflicts if you import two functions with the same name from different modules.

3. Using an Alias

If a module has a long name, you can give it a shorter alias using the as keyword.

import very_long_module_name as short_name

short_name.do_something()

This is very common with popular libraries, like import pandas as pd or import numpy as np.

The Python Standard Library

Python comes with a huge standard library, which is a collection of modules for common tasks. You don't need to install anything to use them; you just need to import them.

  • The math module provides mathematical functions.
  • The datetime module provides classes for working with dates and times.
  • The os module provides a way to interact with the operating system.
  • The random module provides functions for generating random numbers.
import math

print(math.sqrt(16)) # 4.0

import random

print(random.randint(1, 10)) # A random integer between 1 and 10

Packages: Modules in a Directory

When your project gets even larger, you might want to group several related modules together. You can do this by placing them in a directory. A directory that contains modules is called a package. To tell Python to treat a directory as a package, you simply place an __init__.py file inside it (even an empty one).

Conclusion

Modules are the fundamental way to organize and structure a Python application. They allow you to break your code into logical, reusable files, which makes your programs easier to read, maintain, and scale. By understanding how to create and import modules, you've learned a core concept that is essential for any Python project beyond a simple script.