When running this code below I got an
AttributError:
__enter__
I looked around with no success.
import contextvars
# Création d'une variable de contexte
user_context = contextvars.ContextVar("user")
# Définition de la valeur de la variable dans le contexte actuel
with user_context.set("utilisateur123"):
# Cette valeur est accessible à l'intérieur de ce bloc
print(user_context.get()) # Affiche "utilisateur123"
# En dehors du bloc, la valeur redevient celle par défaut (None)
print(user_context.get()) # Affiche "None"
You are probably confusing the two uses of the word "context" here - the fact is that contextvars, as provided in the module with that name, do not work as Python contexts - the type of objects that work in the
withstatement. (Although such an interface would make sense, and I do implement it in my personal, unfinished, project at https://github.com/jsbueno/extracontext )The correct way to execute some code in a separate context, is by containing it in a function and call it by using the
.run()method in a context: