Skip to content

Commit

Permalink
Redone CVar storage as a dict of contextvars
Browse files Browse the repository at this point in the history
  • Loading branch information
spanezz committed Oct 10, 2024
1 parent 18c06d4 commit 8f2d5e1
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,38 @@
import contextlib
import contextvars
import threading
from typing import Any, Dict, Union
from typing import Any, Union


class _CVar:
"""Storage utility for Local."""

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

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

try:
return var.get()
except LookupError:
raise AttributeError(f"{self!r} object has no attribute {key!r}")

def __setattr__(self, key: str, value: Any) -> None:
if key == "_data":
return super().__setattr__(key, value)

storage_object = self._data.get({})
storage_object[key] = value
self._data.set(storage_object)
var = self._data.get(key)
if var is None:
self._data[key] = var = contextvars.ContextVar(key)
var.set(value)

def __delattr__(self, key: str) -> None:
storage_object = self._data.get({})
if key in storage_object:
del storage_object[key]
self._data.set(storage_object)
if key in self._data:
del self._data[key]
else:
raise AttributeError(f"{self!r} object has no attribute {key!r}")

Expand Down

0 comments on commit 8f2d5e1

Please sign in to comment.