What are Python modules?
In Python, a module is a file containing Python definitions and statements. The filename is the module name with the suffix `.py`. Modules allow you to logically organize your Python code, making it reusable and easier to manage.
What is a Python Module?
Essentially, any Python file (.py) can be considered a module. It can define functions, classes, and variables, and can also include runnable code. When you create a Python script and save it with a .py extension, it becomes a module that can be imported and used in other Python scripts or the interactive interpreter.
Key Benefits of Using Modules
- Reusability: Write code once and reuse it across multiple projects without copying and pasting.
- Organization: Break down large programs into smaller, manageable, and logically organized files.
- Namespace Partitioning: Modules help avoid naming conflicts by providing a separate namespace for their contents.
- Maintainability: Changes in one module are localized and less likely to affect other parts of the program, simplifying debugging and updates.
Creating a Simple Module
To create a module, you simply save your Python code in a file with a .py extension. For instance, let's create a file named my_module.py:
# my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
class Calculator:
def add(self, a, b):
return a + b
Using (Importing) a Module
You can use the import statement to bring definitions from a module into another script or the Python interpreter. Once imported, you can access the module's attributes using the dot notation (module_name.attribute).
# main_script.py
import my_module
# Accessing a function
message = my_module.greet("Alice")
print(message)
# Accessing a variable
print(f"Value of PI: {my_module.PI}")
# Accessing a class and its method
calc = my_module.Calculator()
result = calc.add(10, 5)
print(f"10 + 5 = {result}")
You can also import specific attributes using from module import attribute or import all attributes using from module import * (though the latter is generally discouraged for clarity and potential naming conflicts).
from my_module import greet, PI
print(greet("Bob"))
print(PI)
# You can even alias imports
import my_module as mm
print(mm.greet("Charlie"))
Python's Standard Library Modules
Python comes with a rich set of built-in modules, collectively known as the Python Standard Library. These modules provide functionalities for a wide range of tasks, such as mathematical operations, file I/O, operating system interfaces, networking, and much more.
import math
import os
import sys
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Current working directory: {os.getcwd()}")
print(f"Python version: {sys.version}")