Herve Meftah
Herve Meftah

Reputation: 1085

Attribut error when using contextvar in python 3.10

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"

Upvotes: -2

Views: 228

Answers (1)

jsbueno
jsbueno

Reputation: 110591

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"

Upvotes: 0

Related Questions