Skip to content

Commit 85f7e8e

Browse files
committed
Added __slots__ to several classes
1 parent b7ea84c commit 85f7e8e

6 files changed

Lines changed: 84 additions & 18 deletions

File tree

‎docs/versionhistory.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
2727
any ``ReadableBuffer``, thus allowing it to accept ``bytearray`` and ``memoryview`` to
2828
match ``pathlib.Path.write_bytes()``
2929
(`#1135 <https://github.com/agronholm/anyio/issues/1135>`_; PR by @SAY-5)
30+
- Changed several classes (and their subclasses) to have ``__slots__`` (with
31+
``__weakref__``):
32+
33+
* ``anyio.CancelScope``
34+
* ``anyio.CapacityLimiter``
35+
* ``anyio.Condition``
36+
* ``anyio.Event``
37+
* ``anyio.Lock``
38+
* ``anyio.ResourceGuard``
39+
* ``anyio.Semaphore``
3040
- Fixed cancellation exception escaping a cancel scope when triggered via
3141
``check_cancelled()`` in a worker thread
3242
(`#1113 <https://github.com/agronholm/anyio/issues/1113>`_)

‎src/anyio/_backends/_asyncio.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,22 @@ def is_anyio_cancellation(exc: CancelledError) -> bool:
387387

388388

389389
class CancelScope(BaseCancelScope):
390+
__slots__ = (
391+
"_active",
392+
"_cancel_called",
393+
"_cancel_handle",
394+
"_cancel_reason",
395+
"_cancelled_caught",
396+
"_child_scopes",
397+
"_deadline",
398+
"_host_task",
399+
"_parent_scope",
400+
"_pending_uncancellations",
401+
"_shield",
402+
"_tasks",
403+
"_timeout_handle",
404+
)
405+
390406
def __new__(
391407
cls, *, deadline: float = math.inf, shield: bool = False
392408
) -> CancelScope:
@@ -1795,6 +1811,8 @@ async def send(self, item: bytes) -> None:
17951811

17961812

17971813
class Event(BaseEvent):
1814+
__slots__ = ("_event",)
1815+
17981816
def __new__(cls) -> Event:
17991817
return object.__new__(cls)
18001818

@@ -1818,6 +1836,8 @@ def statistics(self) -> EventStatistics:
18181836

18191837

18201838
class Lock(BaseLock):
1839+
__slots__ = "_fast_acquire", "_owner_task", "_waiters"
1840+
18211841
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
18221842
return object.__new__(cls)
18231843

@@ -1892,6 +1912,8 @@ def statistics(self) -> LockStatistics:
18921912

18931913

18941914
class Semaphore(BaseSemaphore):
1915+
__slots__ = "_value", "_max_value", "_fast_acquire", "_waiters"
1916+
18951917
def __new__(
18961918
cls,
18971919
initial_value: int,
@@ -1973,12 +1995,13 @@ def statistics(self) -> SemaphoreStatistics:
19731995

19741996

19751997
class CapacityLimiter(BaseCapacityLimiter):
1976-
_total_tokens: float = 0
1998+
__slots__ = "_total_tokens", "_borrowers", "_wait_queue"
19771999

19782000
def __new__(cls, total_tokens: float) -> CapacityLimiter:
19792001
return object.__new__(cls)
19802002

19812003
def __init__(self, total_tokens: float):
2004+
self._total_tokens: float = 0
19822005
self._borrowers: set[Any] = set()
19832006
self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict()
19842007
self.total_tokens = total_tokens

‎src/anyio/_backends/_trio.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@
111111

112112

113113
class CancelScope(BaseCancelScope):
114+
__slots__ = ("__original",)
115+
114116
def __new__(
115117
cls, original: trio.CancelScope | None = None, **kwargs: object
116118
) -> CancelScope:
@@ -606,6 +608,8 @@ async def send(self, item: bytes) -> None:
606608

607609

608610
class Event(BaseEvent):
611+
__slots__ = ("__original",)
612+
609613
def __new__(cls) -> Event:
610614
return object.__new__(cls)
611615

@@ -627,6 +631,8 @@ def set(self) -> None:
627631

628632

629633
class Lock(BaseLock):
634+
__slots__ = "_fast_acquire", "__original"
635+
630636
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
631637
return object.__new__(cls)
632638

@@ -683,6 +689,8 @@ def statistics(self) -> LockStatistics:
683689

684690

685691
class Semaphore(BaseSemaphore):
692+
__slots__ = ("__original",)
693+
686694
def __new__(
687695
cls,
688696
initial_value: int,
@@ -737,6 +745,8 @@ def statistics(self) -> SemaphoreStatistics:
737745

738746

739747
class CapacityLimiter(BaseCapacityLimiter):
748+
__slots__ = ("__original",)
749+
740750
def __new__(
741751
cls,
742752
total_tokens: float | None = None,

‎src/anyio/_core/_synchronization.py‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ class SemaphoreStatistics:
8080

8181

8282
class Event:
83+
__slots__ = ("__weakref__",)
84+
8385
def __new__(cls) -> Event:
8486
try:
8587
return get_async_backend().create_event()
@@ -110,12 +112,15 @@ def statistics(self) -> EventStatistics:
110112

111113

112114
class EventAdapter(Event):
113-
_internal_event: Event | None = None
114-
_is_set: bool = False
115+
__slots__ = "_internal_event", "_is_set"
115116

116117
def __new__(cls) -> EventAdapter:
117118
return object.__new__(cls)
118119

120+
def __init__(self) -> None:
121+
self._internal_event: Event | None = None
122+
self._is_set = False
123+
119124
@property
120125
def _event(self) -> Event:
121126
if self._internal_event is None:
@@ -148,6 +153,8 @@ def statistics(self) -> EventStatistics:
148153

149154

150155
class Lock:
156+
__slots__ = ("__weakref__",)
157+
151158
def __new__(cls, *, fast_acquire: bool = False) -> Lock:
152159
try:
153160
return get_async_backend().create_lock(fast_acquire=fast_acquire)
@@ -196,12 +203,13 @@ def statistics(self) -> LockStatistics:
196203

197204

198205
class LockAdapter(Lock):
199-
_internal_lock: Lock | None = None
206+
__slots__ = "_internal_lock", "_fast_acquire"
200207

201208
def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter:
202209
return object.__new__(cls)
203210

204211
def __init__(self, *, fast_acquire: bool = False):
212+
self._internal_lock: Lock | None = None
205213
self._fast_acquire = fast_acquire
206214

207215
@property
@@ -260,9 +268,10 @@ def statistics(self) -> LockStatistics:
260268

261269

262270
class Condition:
263-
_owner_task: TaskInfo | None = None
271+
__slots__ = "__weakref__", "_owner_task", "_lock", "_waiters"
264272

265273
def __init__(self, lock: Lock | None = None):
274+
self._owner_task: TaskInfo | None = None
266275
self._lock = lock or Lock()
267276
self._waiters: deque[Event] = deque()
268277

@@ -371,6 +380,8 @@ def statistics(self) -> ConditionStatistics:
371380

372381

373382
class Semaphore:
383+
__slots__ = "__weakref__", "_fast_acquire"
384+
374385
def __new__(
375386
cls,
376387
initial_value: int,
@@ -455,7 +466,7 @@ def statistics(self) -> SemaphoreStatistics:
455466

456467

457468
class SemaphoreAdapter(Semaphore):
458-
_internal_semaphore: Semaphore | None = None
469+
__slots__ = "_internal_semaphore", "_initial_value", "_max_value"
459470

460471
def __new__(
461472
cls,
@@ -474,6 +485,7 @@ def __init__(
474485
fast_acquire: bool = False,
475486
) -> None:
476487
super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
488+
self._internal_semaphore: Semaphore | None = None
477489
self._initial_value = initial_value
478490
self._max_value = max_value
479491

@@ -514,6 +526,8 @@ def statistics(self) -> SemaphoreStatistics:
514526

515527

516528
class CapacityLimiter:
529+
__slots__ = ("__weakref__",)
530+
517531
def __new__(cls, total_tokens: float) -> CapacityLimiter:
518532
try:
519533
return get_async_backend().create_capacity_limiter(total_tokens)
@@ -630,12 +644,13 @@ def statistics(self) -> CapacityLimiterStatistics:
630644

631645

632646
class CapacityLimiterAdapter(CapacityLimiter):
633-
_internal_limiter: CapacityLimiter | None = None
647+
__slots__ = "_internal_limiter", "_total_tokens"
634648

635649
def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter:
636650
return object.__new__(cls)
637651

638652
def __init__(self, total_tokens: float) -> None:
653+
self._internal_limiter: CapacityLimiter | None = None
639654
self.total_tokens = total_tokens
640655

641656
@property
@@ -736,7 +751,7 @@ class ResourceGuard:
736751
.. versionadded:: 4.1
737752
"""
738753

739-
__slots__ = "action", "_guarded"
754+
__slots__ = "__weakref__", "action", "_guarded"
740755

741756
def __init__(self, action: str = "using"):
742757
self.action: str = action

‎src/anyio/_core/_tasks.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ class CancelScope:
4848
current thread
4949
"""
5050

51+
__slots__ = ("__weakref__",)
52+
5153
def __new__(
5254
cls, *, deadline: float = math.inf, shield: bool = False
5355
) -> CancelScope:

‎tests/test_taskgroups.py‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -272,8 +272,13 @@ async def taskfunc() -> None:
272272
async def test_cancel_with_nested_task_groups() -> None:
273273
"""Regression test for #695."""
274274

275+
from anyio._backends import _asyncio
276+
277+
class EditableCancelScope(_asyncio.CancelScope):
278+
pass
279+
275280
async def shield_task() -> None:
276-
with CancelScope(shield=True) as scope:
281+
with EditableCancelScope(shield=True) as scope:
277282
with mock.patch.object(
278283
scope,
279284
"_deliver_cancellation",
@@ -297,15 +302,16 @@ async def middle_task() -> None:
297302
assert len(middle_cancel_spy.call_args_list) < 10
298303
assert len(outer_cancel_spy.call_args_list) < 10
299304

300-
async with create_task_group() as tg:
301-
with mock.patch.object(
302-
tg.cancel_scope,
303-
"_deliver_cancellation",
304-
wraps=getattr(tg.cancel_scope, "_deliver_cancellation"),
305-
) as outer_cancel_spy:
306-
tg.start_soon(middle_task, name="middle task")
307-
await wait_all_tasks_blocked()
308-
tg.cancel_scope.cancel()
305+
with mock.patch.object(_asyncio, "CancelScope", EditableCancelScope):
306+
async with create_task_group() as tg:
307+
with mock.patch.object(
308+
tg.cancel_scope,
309+
"_deliver_cancellation",
310+
wraps=getattr(tg.cancel_scope, "_deliver_cancellation"),
311+
) as outer_cancel_spy:
312+
tg.start_soon(middle_task, name="middle task")
313+
await wait_all_tasks_blocked()
314+
tg.cancel_scope.cancel()
309315

310316
assert len(outer_cancel_spy.call_args_list) < 10
311317

0 commit comments

Comments
 (0)