Created
July 10, 2022 21:33
-
-
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
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
""" | |
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