PY

Common Standard Library

Python · 8 entries

datetime Module

syntax
from datetime import datetime, date, timedelta
example
from datetime import datetime, timedelta

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

deadline = now + timedelta(days=7, hours=3)
print(f"Due: {deadline:%B %d, %Y}")

parsed = datetime.strptime("2026-04-04", "%Y-%m-%d")
print(parsed.date())
output
2026-04-04 14:30
Due: April 11, 2026
2026-04-04

Note For timezone-aware datetimes, use datetime.now(tz=timezone.utc) instead of datetime.utcnow() which is naive and deprecated since 3.12.

collections Module

syntax
from collections import deque, OrderedDict, ChainMap
example
from collections import deque, ChainMap

# deque: efficient append/pop from both ends
buffer = deque(maxlen=3)
for n in range(5):
    buffer.append(n)
print(list(buffer))

# ChainMap: layered dict lookup
defaults = {"color": "blue", "size": 10}
overrides = {"color": "red"}
config = ChainMap(overrides, defaults)
print(config["color"], config["size"])
output
[2, 3, 4]
red 10

Note deque with maxlen auto-discards oldest items when full (ring buffer). ChainMap searches dicts in order, first match wins. Both are in collections.

functools Module

syntax
from functools import lru_cache, partial, reduce
example
from functools import lru_cache, partial

@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(30))
print(fibonacci.cache_info())

# partial: pre-fill arguments
def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
print(square(7))
output
832040
CacheInfo(hits=28, misses=31, maxsize=128, currsize=31)
49

Note lru_cache requires hashable arguments. For unhashable args, consider cachetools or a manual cache. partial is great for adapting callback signatures.

re (Regular Expressions)

syntax
import re
re.search(pattern, string)
re.findall(pattern, string)
example
import re

text = "Contact: [email protected] or [email protected]"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(emails)

# Named groups
log = "2026-04-04 ERROR: Connection timeout"
match = re.match(r"(?P<date>[\d-]+) (?P<level>\w+): (?P<msg>.+)", log)
if match:
    print(match.group("level"), match.group("msg"))
output
['[email protected]', '[email protected]']
ERROR Connection timeout

Note Always use raw strings (r'...') for regex patterns. For repeated use, compile with re.compile() for performance. Use re.VERBOSE for readable multi-line patterns.

typing Module Essentials

syntax
from typing import Optional, Union, TypeVar, Generic
example
from typing import TypeVar, Generic

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

stack = Stack[int]()
stack.push(42)
print(stack.pop())
output
42

Note Since 3.10, use X | Y instead of Union[X, Y]. Since 3.12, use the type parameter syntax: class Stack[T]: instead of TypeVar + Generic.

os and os.path

syntax
import os
os.path.join()
os.environ
example
import os

# Environment variables
db_host = os.environ.get("DB_HOST", "localhost")
print(f"DB: {db_host}")

# Path operations (prefer pathlib for new code)
print(os.path.expanduser("~"))
print(os.path.splitext("report.pdf"))
print(os.getcwd())
output
DB: localhost
/Users/username
('report', '.pdf')
/current/directory

Note Prefer pathlib.Path for path manipulation in new code. os.environ provides direct access to environment variables. Use os.getenv() for safe access with defaults.

json Module (Detailed)

syntax
json.dumps(obj, indent=2)
json.loads(string)
example
import json
from datetime import datetime

# Custom serializer for non-JSON types
def custom_encoder(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Not serializable: {type(obj)}")

event = {"name": "Launch", "when": datetime(2026, 4, 4, 12, 0)}
print(json.dumps(event, default=custom_encoder, indent=2))
output
{
  "name": "Launch",
  "when": "2026-04-04T12:00:00"
}

Note json.dumps raises TypeError for non-serializable types. Pass default= for custom serialization. For complex cases, subclass json.JSONEncoder.

subprocess Module

syntax
import subprocess
subprocess.run([cmd, args], capture_output=True)
example
import subprocess

result = subprocess.run(
    ["echo", "Hello from subprocess"],
    capture_output=True, text=True
)
print(result.stdout.strip())
print(f"Return code: {result.returncode}")
output
Hello from subprocess
Return code: 0

Note Always pass commands as a list, not a string. Use shell=True only when absolutely necessary — it introduces shell injection risks.