What Are Modules?
• Definition: A module is a Python file (.py) containing functions, classes, or variables that can be reused.
• Real-Life Analogy: Think of a module as a toolbox. Instead of reinventing the wheel, you use tools from the toolbox to solve problems.
Why Use Modules?
1. Code Reusability: Write once, use many times.
2. Modularity: Break large programs into smaller, manageable files.
3. Pre-Built Libraries: Leverage Python's extensive standard library and third-party modules.
4. Collaboration: Easier for teams to work on different modules of a project.
Importing Modules
1. Importing the Entire Module# Import the entire math module import math # Use math functions print(math.sqrt(16)) # 4.0 print(math.pi) # 3.1415926535897932. Importing Specific Functions or Variables
# Import only specific functions from math import sqrt, pi print(sqrt(25)) # 5.0 print(pi) # 3.1415926535897933. Importing with Aliases
# Import and alias the module import math as m print(m.sqrt(36)) # 6.04. Importing All Symbols (Not Recommended)
from math import * print(sqrt(49)) # 7.0 print(pi) # 3.141592653589793
⚠ Caution: Avoid this as it can lead to conflicts if multiple modules have functions with the same name.
How to Create and Import Your Own Module
1. Create a Module File: Save the following code as mymodule.py:
def greet(name): return f"Hello, {name}!" pi_value = 3.142. Import Your Module:
import mymodule print(mymodule.greet("Alice")) # Hello, Alice! print(mymodule.pi_value) # 3.143. Import Specific Components:
from mymodule import greet, pi_value print(greet("Bob")) # Hello, Bob! print(pi_value) # 3.14
Real-Life Applications
1. Using Built-in Modules
• os: Interact with the operating system.
• datetime: Work with dates and times.
• random: Generate random numbers.
import os import datetime import random print(os.getcwd()) # Get current working directory print(datetime.datetime.now()) # Current date and time print(random.randint(1, 100)) # Random number between 1 and 100
2. Using Third-Party Modules
Install using pip: pip install requests
Example: Fetching data from the web using requests.
import requests response = requests.get("https://api.github.com") print(response.status_code) # 200
3. Modular Code Design
• Structure: Split a large project into multiple files.
Example: project/ │ ├── main.py # Entry point ├── user.py # Module for user-related functions └── product.py # Module for product-related functions • user.py: def create_user(name): return f"User {name} created." • product.py: def list_products(): return ["Product A", "Product B"] • main.py: from user import create_user from product import list_products print(create_user("Alice")) print(list_products())
Common Pitfalls and Best Practices
1. Avoid Circular Imports:
2. Use Descriptive Module Names:
python -m venv env source env/bin/activate # Linux/Mac env\Scripts\activate # Windows4. Use __name__ == "__main__":
# mymodule.py def greet(name): return f"Hello, {name}!" if __name__ == "__main__": print(greet("Testing"))
Advanced Topics
1. Exploring the Python Standard Library
Python's standard library includes powerful modules like:
• re: Regular expressions.
• json: Working with JSON data.
• itertools: Tools for iterators.
from itertools import permutations data = [1, 2, 3] perms = list(permutations(data)) print(perms) # All possible arrangements of [1, 2, 3]
2. Importing from Packages
Packages are directories with an __init__.py file that can contain multiple modules.
Structure:my_package/ │ ├── __init__.py # Makes it a package ├── module1.py └── module2.pyUsage:
my_package import module1
Recap
Modules | Import Techniques | Best Practices |
---|---|---|
Built-in: math, os, random. Third-party: requests, pandas. Custom: Write and import your own. |
Full module: import module. Specific components: from module import func. Aliases: import module as alias. |
Modularize code. Avoid circular imports. Leverage Python’s standard library. |