Created
May 7, 2025 13:37
-
-
Save MaddyGuthridge/00cca7823839eadb6dc41ea2927912dd to your computer and use it in GitHub Desktop.
Python scope captures are neat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| A quick demo of how scope capturing works in Python. | |
| This code works because inner functions capture a reference | |
| to the original function's scope when they get defined, | |
| rather than a shallow copy of it. | |
| It's so janky and weird, and yet it makes perfect sense. | |
| It's almost poetic. I love Python so much. | |
| """ | |
| def reactive_state(): | |
| a = 0 | |
| def inc(): | |
| nonlocal a | |
| a += 1 | |
| def dec(): | |
| nonlocal a | |
| a -= 1 | |
| def get(): | |
| return a | |
| return inc, dec, get | |
| inc, dec, get = reactive_state() | |
| inc() | |
| inc() | |
| inc() | |
| print(get()) # 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment