Last active
October 4, 2019 14:56
-
-
Save NickBeeuwsaert/a6e081c0a752a667920a77a9d132ce4d to your computer and use it in GitHub Desktop.
Use react's context API in python!
This file contains 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
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 |
This file contains 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
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