-2

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"
2
  • Show the full traceback of the error as properly formatted text (formatted as code) in the question. Commented Nov 10, 2023 at 16:39
  • 2
    A context variable is not a context manager, you can't use it with with. Commented Nov 10, 2023 at 16:49

1 Answer 1

0

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 with statement. (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:


import contextvars

# Création d'une variable de contexte
user_context = contextvars.ContextVar("user")

def my_code():
    """this function will run in an independent copy of the outter context"""
    # Définition de la valeur de la variable dans le contexte actuel
    user_context.set("utilisateur123"):
    # Cette valeur est accessible à l'intérieur de ce bloc
    print(user_context.get())  # Affiche "utilisateur123"

my_context = contextvars.copy_context()
my_context.run(my_code)

# En dehors du bloc, la valeur redevient celle par défaut (None)
print(user_context.get())  # Affiche "None"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.