asAdvanced Examples

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

as in type annotations and walrus

Less common uses of 'as' keyword.

python
# as in import is compile-time aliasing
import collections.abc as abc
print(f"abc module: {abc.__name__}")

# as in except creates a scoped variable (Python 3)
# The variable is deleted after the except block!
try:
    raise ValueError("test")
except ValueError as e:
    captured = str(e)
    # e is available here

# After except block, e is deleted
try:
    print(e)
except NameError:
    print(f"'e' was deleted after except block")
print(f"But captured = {captured}")

# Note: walrus (:=) is NOT the same as 'as'
# := assigns in expressions (Python 3.8+)
# as is for imports, except, with, and match
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
    print(f"Long list: {n} items")

In Python 3, the 'as' variable in except blocks is automatically deleted after the block exits. This prevents reference cycles with tracebacks.

Want to try these examples interactively?

Open Advanced Playground