Python's module system lets you organize code into reusable files and directories. With pip, you have access to 400,000+ packages.
Importing Modules
Python
# Import entire module
import math
print(math.sqrt(16)) # 4.0
# Import specific items
from math import sqrt, pi
print(sqrt(16)) # 4.0 (no math. prefix needed)
print(pi) # 3.14159...
# Import with alias
import numpy as np
from datetime import datetime as dt
# Import everything (DON'T do this — namespace pollution!)
from math import *Creating Your Own Modules
Python
# mymodule.py
"""A helpful utilities module."""
__version__ = "1.0.0"
def greet(name: str) -> str:
"""Return a greeting message."""
return f"Hello, {name}!"
class Timer:
"""Simple timer context manager."""
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, *args):
import time
self.elapsed = time.time() - self.start
# main.py
from mymodule import greet, Timer
import mymodule
print(greet("Alice"))
print(mymodule.__version__)
with Timer() as t:
sum(range(1000000))
print(f"Elapsed: {t.elapsed:.4f}s")Standard Library Highlights
Python
# collections — specialized containers
from collections import Counter, defaultdict, namedtuple
# Counter — count occurrences
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_counts = Counter(words)
print(word_counts.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict — dict with default values
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd) # {'fruits': ['apple', 'banana']}
# datetime — date and time
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(now.strftime("%Y-%m-%d %H:%M:%S")) # "2024-01-15 14:30:00"
# json — JSON parsing
import json
data = '{"name": "Alice", "age": 28}'
parsed = json.loads(data)
print(parsed["name"]) # "Alice"
# re — regular expressions
import re
email = "user@example.com"
if re.match(r'^[\w.-]+@[\w.-]+\.\w+$', email):
print("Valid email!")
# itertools — iterator tools
import itertools
for combo in itertools.combinations([1, 2, 3, 4], 2):
print(combo) # (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)Virtual Environments
Python
# Create a virtual environment
python3 -m venv myenv
# Activate
source myenv/bin/activate # macOS/Linux
myenv\Scripts\activate # Windows
# Install packages (only in this environment)
pip install requests flask
# Save dependencies
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txt
# Deactivate
deactivatePyPI and pip
Bash
# Search for packages
pip search requests # (deprecated, use pypi.org instead)
# Install packages
pip install flask
pip install flask==2.3.0 # Specific version
pip install flask>=2.0,<3.0 # Version range
# Upgrade packages
pip install --upgrade flask
# Uninstall
pip uninstall flask
# List installed packages
pip list
pip show flaskKnowledge Check
4 questions — test your understanding
1
What is the purpose of `import math as m`?
2
What does `from collections import Counter` give you?
3
Why should you use virtual environments?
4
What does `pip freeze > requirements.txt` do?