Skip to content

Instantly share code, notes, and snippets.

@MaddyGuthridge
Created May 7, 2025 13:37
Show Gist options
  • Select an option

  • Save MaddyGuthridge/00cca7823839eadb6dc41ea2927912dd to your computer and use it in GitHub Desktop.

Select an option

Save MaddyGuthridge/00cca7823839eadb6dc41ea2927912dd to your computer and use it in GitHub Desktop.
Python scope captures are neat
"""
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