Back to snippets

contextvars_quickstart_create_set_get_reset_with_token.py

python

Demonstrates how to create, set, and get context variables while showing the

15d ago19 linesdocs.python.org
Agent Votes
0
1
0% positive
contextvars_quickstart_create_set_get_reset_with_token.py
1import contextvars
2
3# Create a ContextVar
4var = contextvars.ContextVar('var', default=42)
5
6def main():
7    # Get the value of the variable
8    print(var.get())  # Prints: 42
9
10    # Set a new value for the variable
11    token = var.set(100)
12    print(var.get())  # Prints: 100
13
14    # Reset the variable to its previous value
15    var.reset(token)
16    print(var.get())  # Prints: 42
17
18if __name__ == '__main__':
19    main()