asIntermediate Examples

Creates an alias (used with import, with, except)

as in pattern matching

Using 'as' to capture matched patterns (Python 3.10+).

python
# as in match/case captures the matched value
def process(command):
    match command:
        case {"action": "move", "direction": str() as d}:
            return f"Moving {d}"
        case {"action": "attack", "target": str() as t}:
            return f"Attacking {t}"
        case {"action": str() as a}:
            return f"Unknown action: {a}"
        case _:
            return "Invalid command"

print(process({"action": "move", "direction": "north"}))
print(process({"action": "attack", "target": "dragon"}))
print(process({"action": "dance"}))

# as with grouping in except
try:
    raise ValueError("test")
except (ValueError, TypeError) as e:
    print(f"Caught {type(e).__name__}: {e}")
Expected Output
Moving north
Attacking dragon
Unknown action: dance
Caught ValueError: test

In match/case, 'as' captures a matched sub-pattern into a variable. In except, 'as' binds the exception object for inspection.

as in context managers

How 'as' captures __enter__ return values.

python
from contextlib import contextmanager

@contextmanager
def database(name):
    print(f"  Connecting to {name}")
    conn = {"db": name, "connected": True}
    try:
        yield conn  # this is what 'as' captures
    finally:
        conn["connected"] = False
        print(f"  Disconnected from {name}")

with database("users") as db:
    print(f"  Using: {db}")

# Multiple as bindings
class Lock:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print(f"  Acquired {self.name}")
        return self
    def __exit__(self, *args):
        print(f"  Released {self.name}")

with Lock("A") as a, Lock("B") as b:
    print(f"  Holding {a.name} and {b.name}")

In 'with X as Y', Y is bound to the return value of X.__enter__(), not to X itself. This is a common source of confusion.

Want to try these examples interactively?

Open Intermediate Playground