Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-105726: Add __slots__ to AbstractContextManager and AbstractAsyncContextManager #106771

Merged
merged 7 commits into from
Jul 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class AbstractContextManager(abc.ABC):

__class_getitem__ = classmethod(GenericAlias)

__slots__ = ()

def __enter__(self):
"""Return `self` upon entering the runtime context."""
return self
Expand All @@ -42,6 +44,8 @@ class AbstractAsyncContextManager(abc.ABC):

__class_getitem__ = classmethod(GenericAlias)

__slots__ = ()

async def __aenter__(self):
"""Return `self` upon entering the runtime context."""
return self
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ def __exit__(self, *args):
manager = DefaultEnter()
self.assertIs(manager.__enter__(), manager)

def test_slots(self):
class DefaultContextManager(AbstractContextManager):
__slots__ = ()

def __exit__(self, *args):
super().__exit__(*args)

with self.assertRaises(AttributeError):
DefaultContextManager().var = 42

def test_exit_is_abstract(self):
class MissingExit(AbstractContextManager):
pass
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_contextlib_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ async def __aexit__(self, *args):
async with manager as context:
self.assertIs(manager, context)

@_async_test
async def test_slots(self):
class DefaultAsyncContextManager(AbstractAsyncContextManager):
__slots__ = ()

async def __aexit__(self, *args):
await super().__aexit__(*args)

with self.assertRaises(AttributeError):
manager = DefaultAsyncContextManager()
manager.var = 42

@_async_test
async def test_async_gen_propagates_generator_exit(self):
# A regression test for https://bugs.python.org/issue33786.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Added ``__slots__`` to :class:`contextlib.AbstractContextManager` and :class:`contextlib.AbstractAsyncContextManager`
so that child classes can use ``__slots__``.

Loading