# as in import is compile-time aliasingimport 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 deletedtry:
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")
Output
Click "Run" to execute your code
In Python 3, the 'as' variable in except blocks is automatically deleted after the block exits. This prevents reference cycles with tracebacks.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?