Skip to content

Instantly share code, notes, and snippets.

@NickBeeuwsaert
Last active October 4, 2019 14:56
Show Gist options
  • Save NickBeeuwsaert/a6e081c0a752a667920a77a9d132ce4d to your computer and use it in GitHub Desktop.
Save NickBeeuwsaert/a6e081c0a752a667920a77a9d132ce4d to your computer and use it in GitHub Desktop.
Use react's context API in python!
from contextlib import contextmanager
import threading
def use_context(context):
with context.consumer() as value:
return value
class Context(threading.local):
def __init__(self, default = None):
self.value = default
@contextmanager
def provider(self, value):
old_value = self.value
self.value = value
yield
self.value = old_value
@contextmanager
def consumer(self):
yield self.value
create_context = Context
from context import create_context, use_context
ctx = create_context(123)
def inner_fn():
with ctx.consumer() as value:
print(f"inner_fn: value = {value}")
def some_fn():
value = use_context(ctx)
print(f"some_fn: value = {value}")
with ctx.provider(12):
inner_fn()
print(f"some_fn: value = {value}")
some_fn()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment