home blog portfolio Ian Fisher

Python cheatsheet

See also: wiki/python

Get script path

import os

os.path.abspath(__file__)

match statement

match value:
    case pat1:
        # ...
    case pat2 | pat3 if pat3 > 0:
        # ...
    case ["x", ("y" | "z") as myvar]:
        # ...
    case _:
        # ...

Spawn a subprocess

import subprocess

proc = subprocess.run(["cat", "myfile"], check=True, capture_output=True, text=True)
# proc.stdout
# proc.stderr
# proc.returncode

Generator types

from typing import Generator

def my_generator() -> Generator[T, None, None]:
    # ...
import traceback

try:
    whatever()
except Exception:
    print(traceback.format_exc())

# as string (can be outside exception handler)
"".join(traceback.format_stack())

# raw stack
traceback.extract_stack()


import sys
import traceback
from types import TracebackType
from typing import Type

exc_type, exc_value, exc_traceback = sys.exc_info()

def handle_exception(
    exc_type: Type[BaseException],
    exc_value: BaseException,
    exc_traceback: TracebackType
):
    print("".join(traceback.format_tb(exc_traceback)))

Annotated dataclass fields

from typing import Annotated

@dataclass
class Point:
    lat: Annotated[float, "latitude"]
    lng: Annotated[float, "longitude"]

Point.__dataclass_fields__["lat"].type.__metadata__[0]

Context managers

from contextlib import contextmanager

@contextmanager
def my_manager():
  # setup
  try:
    yield value
  finally:
    # cleanup


class MyManager:
  def __enter__(self):
    # setup
    return value

  def __exit__(self, exc_type, exc_value, traceback):
    # cleanup

See also