@@ -30,10 +30,11 @@ class Context(contextlib.ContextDecorator):
30
30
stack : ClassVar [List [dict [str , int ]]] = [{}]
31
31
def __init__ (self , ** kwargs ): self .kwargs = kwargs
32
32
def __enter__ (self ):
33
- for k ,v in self .kwargs .items (): ContextVar ._cache [k ].value = v
34
- Context .stack .append (self .kwargs )
33
+ Context .stack [- 1 ] = {k :o .value for k ,o in ContextVar ._cache .items ()} # Store current state.
34
+ for k ,v in self .kwargs .items (): ContextVar ._cache [k ].value = v # Update to new temporary state.
35
+ Context .stack .append (self .kwargs ) # Store the temporary state so we know what to undo later.
35
36
def __exit__ (self , * args ):
36
- for k in Context .stack .pop (): ContextVar ._cache [k ].value = Context .stack [- 1 ].get (k , Context . stack [ 0 ][ k ] )
37
+ for k in Context .stack .pop (): ContextVar ._cache [k ].value = Context .stack [- 1 ].get (k , ContextVar . _cache [ k ]. value )
37
38
38
39
class ContextVar :
39
40
_cache : ClassVar [Dict [str , ContextVar ]] = {}
@@ -42,7 +43,7 @@ class ContextVar:
42
43
def __new__ (cls , key , default_value ):
43
44
if key in ContextVar ._cache : return ContextVar ._cache [key ]
44
45
instance = ContextVar ._cache [key ] = super ().__new__ (cls )
45
- instance .value = Context . stack [ 0 ][ key ] = getenv (key , default_value )
46
+ instance .value = getenv (key , default_value )
46
47
return instance
47
48
def __bool__ (self ): return bool (self .value )
48
49
def __ge__ (self , x ): return self .value >= x
0 commit comments