Module

In Python, a module is a file containing Python code, which can define functions, classes, variables, and more. It can also include runnable code.

Modules allow you to organize your Python code into manageable parts, making it easier to maintain and reuse. Each module has its own namespace, meaning that the variables, functions, and classes defined in a module can be accessed using dot notation, which helps to avoid naming conflicts.

Python provides a rich standard library of modules that you can use to perform a wide variety of tasks, from file I/O to mathematical computations. You can also create your own modules to organize your code. To use a module, you typically import it using the import statement.

Example

Here’s a simple example of creating and using a module in Python. First, create a file named module.py with the following content:

Python module.py
def greet(name):
    return f"Hello, {name}!"

Now, you can use this module in a Python script:

Python main.py
import module

message = module.greet("Real Python")
print(message)  # Output: 'Hello, Real Python!'

To use a module from another Python file, you typically import it using an import statement as you did in the code. Once imported, you can use the module’s content in your code.

Tutorial

Python Modules and Packages – An Introduction

This article explores Python modules and Python packages, two mechanisms that facilitate modular programming.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 2, 2025 • Reviewed by Dan Bader