Skip to content

Commit 5736cd8

Browse files
committed
Get rid of context manager object altogether
Thanks to bluetech for the idea.
1 parent ece894a commit 5736cd8

1 file changed

Lines changed: 19 additions & 25 deletions

File tree

asgiref/local.py

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -36,23 +36,6 @@ def __delattr__(self, key: str) -> None:
3636
raise AttributeError(f"{self!r} object has no attribute {key!r}")
3737

3838

39-
class _LockContext:
40-
"""Context manager that acquires a lock and yields a value."""
41-
42-
__slots__ = ("_lock", "_value")
43-
44-
def __init__(self, lock: threading.RLock, value: Any) -> None:
45-
self._lock = lock
46-
self._value = value
47-
48-
def __enter__(self):
49-
self._lock.acquire()
50-
return self._value
51-
52-
def __exit__(self, *exc_info):
53-
self._lock.release()
54-
55-
5639
_object_setattr = object.__setattr__
5740

5841

@@ -111,21 +94,32 @@ class _DefaultLocal(Local):
11194
def __init__(self, thread_critical: bool = False) -> None:
11295
super().__init__(thread_critical)
11396
storage = _CVar()
114-
lock = threading.RLock()
97+
_object_setattr(self, "_lock", threading.RLock())
11598
_object_setattr(self, "_storage", storage)
116-
_object_setattr(self, "_lock_context", _LockContext(lock, storage))
11799

118100
def __getattr__(self, key):
119-
with self._lock_context as storage:
120-
return getattr(storage, key)
101+
# Lock acquisition inlined here for performance reasons.
102+
try:
103+
self._lock.acquire()
104+
return getattr(self._storage, key)
105+
finally:
106+
self._lock.release()
121107

122108
def __setattr__(self, key, value):
123-
with self._lock_context as storage:
124-
setattr(storage, key, value)
109+
# Lock acquisition inlined here for performance reasons.
110+
try:
111+
self._lock.acquire()
112+
setattr(self._storage, key, value)
113+
finally:
114+
self._lock.release()
125115

126116
def __delattr__(self, key):
127-
with self._lock_context as storage:
128-
delattr(storage, key)
117+
# Lock acquisition inlined here for performance reasons.
118+
try:
119+
self._lock.acquire()
120+
delattr(self._storage, key)
121+
finally:
122+
self._lock.release()
129123

130124

131125
class _ThreadCriticalLocal(Local):

0 commit comments

Comments
 (0)