Skip to content

Commit 55408f8

Browse files
gh-105726: Add __slots__ to AbstractContextManager and AbstractAsyncContextManager (#106771)
Co-authored-by: Kumar Aditya <[email protected]>
1 parent cc25ca1 commit 55408f8

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

Lib/contextlib.py

+4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ class AbstractContextManager(abc.ABC):
2020

2121
__class_getitem__ = classmethod(GenericAlias)
2222

23+
__slots__ = ()
24+
2325
def __enter__(self):
2426
"""Return `self` upon entering the runtime context."""
2527
return self
@@ -42,6 +44,8 @@ class AbstractAsyncContextManager(abc.ABC):
4244

4345
__class_getitem__ = classmethod(GenericAlias)
4446

47+
__slots__ = ()
48+
4549
async def __aenter__(self):
4650
"""Return `self` upon entering the runtime context."""
4751
return self

Lib/test/test_contextlib.py

+10
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@ def __exit__(self, *args):
2424
manager = DefaultEnter()
2525
self.assertIs(manager.__enter__(), manager)
2626

27+
def test_slots(self):
28+
class DefaultContextManager(AbstractContextManager):
29+
__slots__ = ()
30+
31+
def __exit__(self, *args):
32+
super().__exit__(*args)
33+
34+
with self.assertRaises(AttributeError):
35+
DefaultContextManager().var = 42
36+
2737
def test_exit_is_abstract(self):
2838
class MissingExit(AbstractContextManager):
2939
pass

Lib/test/test_contextlib_async.py

+12
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ async def __aexit__(self, *args):
3737
async with manager as context:
3838
self.assertIs(manager, context)
3939

40+
@_async_test
41+
async def test_slots(self):
42+
class DefaultAsyncContextManager(AbstractAsyncContextManager):
43+
__slots__ = ()
44+
45+
async def __aexit__(self, *args):
46+
await super().__aexit__(*args)
47+
48+
with self.assertRaises(AttributeError):
49+
manager = DefaultAsyncContextManager()
50+
manager.var = 42
51+
4052
@_async_test
4153
async def test_async_gen_propagates_generator_exit(self):
4254
# A regression test for https://bugs.python.org/issue33786.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Added ``__slots__`` to :class:`contextlib.AbstractContextManager` and :class:`contextlib.AbstractAsyncContextManager`
2+
so that child classes can use ``__slots__``.
3+

0 commit comments

Comments
 (0)