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:
module.py
def greet(name):
return f"Hello, {name}!"
Now, you can use this module in a Python script:
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.
Related Resources
Tutorial
Python Modules and Packages – An Introduction
This article explores Python modules and Python packages, two mechanisms that facilitate modular programming.
For additional information on related topics, take a look at the following resources:
- Python's __all__: Packages, Modules, and Wildcard Imports (Tutorial)
- Python Zip Imports: Distribute Modules and Packages Quickly (Tutorial)
- Python import: Advanced Techniques and Tips (Tutorial)
- Python Modules and Packages: An Introduction (Course)
- Python Modules and Packages (Quiz)
- Advanced Python import Techniques (Course)
- Python import: Advanced Techniques and Tips (Quiz)