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.
Step through the example below to watch import module add a single name, module, to the namespace of main.py, while greet stays inside the module’s own namespace:
The widget opens on the finished run, with Hello, Real Python! under Output. Click Start over, then Next, to replay it. Each step highlights the current line in both files and fills in the main.py namespace and module namespace panels. On step 3, the chips read “found module” in main.py and “found greet” inside the module, which is the lookup that the dot performs.
Now switch Line 3 calls to greet(). Python looks up a bare greet in main.py only, which holds just module, so the chip reads “no greet”, line 3 turns red, and Output shows NameError: name 'greet' is not defined.
Related Resources
Tutorial
Python Modules and Packages – An Introduction
Explore Python modules and packages, the two mechanisms that make modular programming possible, and learn how imports find your code.
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)
- Managing Imports With Python's __all__ (Course)
- Python's __all__: Packages, Modules, and Wildcard Imports (Quiz)
- Advanced Python import Techniques (Course)
- Python import: Advanced Techniques and Tips (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.