as — Intermediate Playground
Creates an alias (used with import, with, except)
Python Playground
# 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}")
Output
Click "Run" to execute your code
In match/case, 'as' captures a matched sub-pattern into a variable. In except, 'as' binds the exception object for inspection.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?