finally — Expert Examples
Block that always executes after try/except, used for cleanup
finally bytecode
How finally is compiled in CPython.
python
import dis def try_finally(): try: x = 1 finally: y = 2 def full_pattern(): try: x = 1 except ValueError: x = 2 else: x = 3 finally: x = 4 print("try/finally:") dis.dis(try_finally) print("\nfull pattern:") dis.dis(full_pattern) # The finally block is duplicated in the bytecode: # once for the normal path and once for the exception path. # This ensures it runs regardless of how the try exits.
CPython duplicates the finally block's bytecode into both the normal and exception paths. SETUP_FINALLY pushes an entry onto the block stack that the VM uses to find the cleanup code.
Want to try these examples interactively?
Open Expert Playground