Skip to content

Instantly share code, notes, and snippets.

@Ambro17
Created July 10, 2022 21:33
Show Gist options
  • Save Ambro17/66d79703184497be5895de463df74074 to your computer and use it in GitHub Desktop.
Save Ambro17/66d79703184497be5895de463df74074 to your computer and use it in GitHub Desktop.
Here we try to imitate Flask global objects magic in which `from flask import request` magically finds the current request. We use contextvars to make it more understandable, as a con it requires calling `.get()` instead of just using the imported module attribute. I like this since it doesn't hide the fact that the object is lazily evaluated
"""
Here we try to imitate Flask global objects magic in which `from flask import request`
magically finds the current request.
We use contextvars to make it more understandable, as a con it requires calling `.get()`
instead of just using the imported module attribute.
I like this since it doesn't hide the fact that the object is lazily evaluated
"""
# This single file represents three modules. app.py, bootstrap.py and settings.py
# Each file's content is preceded by the file name.
# app.py
# Try reading config, fail. Import setup code, then retry and succed
from settings import config
print(config)
try:
config.get()
except LookupError:
print('i failed')
# Now importing the code that sets it up
from bootstrap import *
print(config.get())
# bootstrap.py
# Set the configuration to something
from settings import config
def set_config(value):
config.set(value)
set_config('x')
# settings.py
from contextvars import ContextVar, Token
config: ContextVar = ContextVar('config')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment