Modules in Python
Modules in Python are files containing Python code. They allow you to organize your code into reusable components, making it easier to maintain and scale your programs. Python also provides a rich standard library of modules for common tasks like file handling, mathematical operations, and more.
Creating a Module
Create a Python file (e.g., mymodule.py
) and define functions, classes, or variables in it.
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
def add(a, b):
return a + b
Importing a Module
Use the import
statement to use a module in your code. You can import the entire module or specific functions.
# Import the entire module
import mymodule
mymodule.greet("Alice")
print(mymodule.add(5, 10)) # Output: 15
# Import specific functions
from mymodule import greet, add
greet("Bob")
print(add(7, 3)) # Output: 10
Standard Library Modules
Python comes with a rich standard library of modules, such as math
, os
, random
, and datetime
.
import math
import os
import random
from datetime import datetime
# Using math module
print(math.sqrt(16)) # Output: 4.0
# Using os module
print(os.getcwd()) # Output: Current working directory
# Using random module
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
# Using datetime module
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Output: Current date and time
Aliasing Modules
You can use aliases to shorten module names when importing them.
import math as m
print(m.sqrt(25)) # Output: 5.0
Installing Third-Party Modules
Python's package manager, pip
, allows you to install third-party modules from the Python Package Index (PyPI).
# Install a third-party module
pip install requests
# Using the installed module
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # Output: 200 (if successful)
Creating a Package
A package is a collection of modules organized in a directory. To create a package, include an __init__.py
file in the directory.
mypackage/
__init__.py
module1.py
module2.py
# Importing from a package
from mypackage import module1, module2
module1.some_function()
module2.another_function()
Module Search Path
Python searches for modules in the directories listed in sys.path
. You can modify this list to include custom directories.
import sys
# Print the module search path
print(sys.path)
# Add a custom directory to the search path
sys.path.append("/path/to/custom/modules")
Reloading a Module
If you modify a module after importing it, you can reload it using the importlib
module.
import importlib
import mymodule
# Reload the module
importlib.reload(mymodule)
Best Practices
- Use meaningful names for modules and packages.
- Organize related functions and classes into the same module.
- Use
if __name__ == "__main__"
to define executable code in a module. - Document your modules using docstrings.
# Example of using __name__ == "__main__"
if __name__ == "__main__":
print("This code runs when the module is executed directly.")
Next: Exception Handling