Stage 7 · Master
Python for Operators
Python Quick Start
Python for engineers who already know code — syntax, types, collections, and comprehensions.
Why Python for DevOps
Python dominates DevOps tooling because of its ecosystem. Every cloud provider, container runtime, and monitoring system has a mature Python SDK. Scripts that would take hundreds of lines in Bash become几十 lines in Python, and they are readable by your entire team.
This course assumes you already know Go, Rust, or another language. You are learning Python to write operational tools, not to become a Python developer. Focus on the standard library and the DevOps-relevant packages.
Installation and REPL
Most modern macOS and Linux systems ship with Python 3.10+. Verify your version before writing any code.
python3 --version
Python 3.12.2
# Start the interactive REPL
python3
>>> import sys
>>> print(sys.version)
3.12.2 (main, Feb 6 2024, 20:19:36) [Clang 15.0.0 (clang-1500.3.9.4)]
>>> exit()The REPL is useful for quick experiments. Use it to test expressions, check module APIs, and prototype logic before writing scripts.
# macOS
brew install pyenv
pyenv install 3.12.2
pyenv global 3.12.2
# Verify
python3 --versionpyenv lets you manage multiple Python versions without touching the system Python. This avoids permission issues and version conflicts.
Types and Variables
Python is dynamically typed but supports type hints. For DevOps scripts, type hints are essential — they make your code self-documenting and enable IDE autocompletion.
from pathlib import Path
# Basic types
name: str = "production"
replicas: int = 3
cpu_limit: float = 0.5
is_healthy: bool = True
# Type hints make your intent explicit
def check_health(endpoint: str, timeout: int = 5) -> bool:
"""Check if a service endpoint is responding."""
return True # placeholder
# Use Union for optional types
from typing import Optional
def get_secret(name: str, default: Optional[str] = None) -> str:
return default or ""Type hints are not enforced at runtime, but tools like mypy and your IDE use them to catch errors before you run the code.
Collections
Python has four built-in collection types. For DevOps work, you will use lists, dicts, and sets constantly.
# Lists — ordered, mutable
servers: list[str] = ["web-01", "web-02", "web-03"]
servers.append("web-04")
# Dicts — key-value, ordered (Python 3.7+)
config: dict[str, str | int] = {
"host": "0.0.0.0",
"port": 8080,
"workers": 4,
}
# Sets — unique, unordered
healthy: set[str] = {"web-01", "web-03"}
all_servers: set[str] = {"web-01", "web-02", "web-03", "web-04"}
unhealthy = all_servers - healthy # {"web-02", "web-04"}
# Tuples — immutable, for fixed structure
endpoint: tuple[str, int] = ("10.0.0.1", 443)Use type hints with collections: list[str], dict[str, int], set[str]. The built-in types work as generic types in Python 3.9+ without importing from typing.
Comprehensions
Comprehensions are Python's most distinctive feature for data transformation. They replace map/filter loops with concise, readable expressions.
# List comprehension — filter and transform
from pathlib import Path
log_files = list(Path("/var/log").glob("*.log"))
large_logs = [f for f in log_files if f.stat().st_size > 1_000_000]
# Dict comprehension — build lookup tables
server_ips = {
"web-01": "10.0.1.1",
"web-02": "10.0.1.2",
"db-01": "10.0.2.1",
}
ip_lookup = {ip: name for name, ip in server_ips.items()}
# Nested — flatten a list of lists
all_endpoints = [["/api/health", "/api/metrics"], ["/health", "/metrics"]]
flat = [ep for group in all_endpoints for ep in group]Comprehensions are faster than equivalent for-loops because Python optimizes them internally. Use them whenever you are filtering or transforming collections.
Virtual Environments
Never install packages globally. Virtual environments isolate dependencies per project and prevent version conflicts.
# Create a venv in the project directory
python3 -m venv .venv
# Activate it
source .venv/bin/activate
# Now pip installs into .venv, not the system
pip install requests pyyaml
# Freeze dependencies
pip freeze > requirements.txt
# Deactivate when done
deactivateThe .venv directory should be in .gitignore. Each developer creates their own. The requirements.txt file is committed to ensure reproducible installs.
A virtual environment is a lightweight directory with a symlinked Python interpreter and its own pip. It takes seconds to create and saves hours of debugging version conflicts.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.