import dis
defimport_as():
import json as j
return j
defexcept_as():
try:
passexcept ValueError as e:
return e
defwith_as():
classCM:
def__enter__(self): return1def__exit__(self, *a): passwith CM() as val:
return val
print("import as:")
dis.dis(import_as)
print("\nexcept as:")
dis.dis(except_as)
print("\nwith as:")
dis.dis(with_as)
# import as: IMPORT_NAME + STORE_FAST (stores under alias name)# except as: STORE_FAST + DELETE_FAST after block# with as: STORE_FAST (stores __enter__ return value)
Output
Click "Run" to execute your code
'as' is not a single bytecode operation — it's syntactic sugar. Import as renames the stored name. Except as stores then deletes the exception. With as stores the __enter__ return value.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?