Modules, Packages, and pip
As programs grow, splitting code across separate files and reusing third-party libraries becomes essential.
What is it?
A Python module is simply a file with a `.py` extension. A package is a directory containing modules. `pip` is the official package manager for Python.
Why is it used?
Organizes code into logical components, enables code sharing, and provides access to over 500,000 open-source packages on PyPI.
Detailed Explanation
Importing Modules:
• `import math`: Access with `math.sqrt(16)`
• `from datetime import datetime`: Direct import
• `import pandas as pd`: Alias import
• The `if __name__ == '__main__':` construct: Checks if the script is being executed directly rather than imported as a module by another file.
Syntax Structure
Syntax Blueprint
import math
from datetime import date
if __name__ == '__main__':
print("Script executed directly")
Code Example
PYTHON Code
# Using Python Standard Library Modules
import math
import random
from datetime import datetime
# Math calculations
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Circle Area (r=5): {area:.2f}")
# Random choice generator for student quiz question
quiz_topics = ["OOP", "Decorators", "Generators", "File I/O", "Recursion"]
chosen_topic = random.choice(quiz_topics)
print(f"Today's Random Pop Quiz Topic: {chosen_topic}")
# Date Formatting
current_time = datetime.now().strftime("%A, %B %d, %Y at %I:%M %p")
print(f"Report Generated: {current_time}")
Explanation of the Code
• Imports `math`, `random`, and `datetime` from the Python standard library.
• Demonstrates `random.choice()` and `datetime.strftime()` string formatting.
Expected Output
Circle Area (r=5): 78.54
Today's Random Pop Quiz Topic: ... (random choice)
Report Generated: ... (current formatted timestamp)
Real-World Application
Every Flask and Django application is structured into modules (`models.py`, `views.py`, `services.py`).
Common Mistakes to Avoid
• Naming your own file after a standard library module (e.g. naming your file `random.py` or `math.py` shadows the real module and causes crashes!).
• Using wildcard imports `from module import *` (pollutes namespace and leads to conflicts).
Quick Practice Challenge
Import the `os` module and print your current working directory using `os.getcwd()`.
Key Takeaways
• A module is a `.py` file; a package is a directory of modules.
• Use `pip install package_name` to install third-party libraries.
• Use `if __name__ == '__main__':` to make scripts safely importable.