Skip to content

Commit 16d4ae2

Browse files
committed
Redone CVar storage as a dict of contextvars
1 parent 4ac25d2 commit 16d4ae2

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

asgiref/local.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,38 @@
22
import contextlib
33
import contextvars
44
import threading
5-
from typing import Any, Dict, Union
5+
from typing import Any, Union
66

77

88
class _CVar:
99
"""Storage utility for Local."""
1010

1111
def __init__(self) -> None:
12-
self._data: "contextvars.ContextVar[Dict[str, Any]]" = contextvars.ContextVar(
13-
"asgiref.local"
14-
)
12+
self._data: dict[str, contextvars.ContextVar[Any]] = {}
1513

16-
def __getattr__(self, key):
17-
storage_object = self._data.get({})
14+
def __getattr__(self, key: str) -> Any:
1815
try:
19-
return storage_object[key]
16+
var = self._data[key]
2017
except KeyError:
2118
raise AttributeError(f"{self!r} object has no attribute {key!r}")
2219

20+
try:
21+
return var.get()
22+
except LookupError:
23+
raise AttributeError(f"{self!r} object has no attribute {key!r}")
24+
2325
def __setattr__(self, key: str, value: Any) -> None:
2426
if key == "_data":
2527
return super().__setattr__(key, value)
2628

27-
storage_object = self._data.get({})
28-
storage_object[key] = value
29-
self._data.set(storage_object)
29+
var = self._data.get(key)
30+
if var is None:
31+
self._data[key] = var = contextvars.ContextVar(key)
32+
var.set(value)
3033

3134
def __delattr__(self, key: str) -> None:
32-
storage_object = self._data.get({})
33-
if key in storage_object:
34-
del storage_object[key]
35-
self._data.set(storage_object)
35+
if key in self._data:
36+
del self._data[key]
3637
else:
3738
raise AttributeError(f"{self!r} object has no attribute {key!r}")
3839

0 commit comments

Comments
 (0)