Skip to content

bpo-30306: release arguments of contextmanager #1500

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

Merged
merged 3 commits into from
Jan 28, 2018
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
3 changes: 3 additions & 0 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ def _recreate_cm(self):
return self.__class__(self.func, self.args, self.kwds)

def __enter__(self):
# do not keep args and kwds alive unnecessarily
# they are only needed for recreation, which is not possible anymore
del self.args, self.kwds, self.func
try:
return next(self.gen)
except StopIteration:
Expand Down
47 changes: 47 additions & 0 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import unittest
from contextlib import * # Tests __all__
from test import support
import weakref


class TestAbstractContextManager(unittest.TestCase):
Expand Down Expand Up @@ -218,6 +219,52 @@ def woohoo(self, func, args, kwds):
with woohoo(self=11, func=22, args=33, kwds=44) as target:
self.assertEqual(target, (11, 22, 33, 44))

def test_nokeepref(self):
class A:
pass

@contextmanager
def woohoo(a, b):
a = weakref.ref(a)
b = weakref.ref(b)
self.assertIsNone(a())
self.assertIsNone(b())
yield

with woohoo(A(), b=A()):
pass

def test_param_errors(self):
@contextmanager
def woohoo(a, *, b):
yield

with self.assertRaises(TypeError):
woohoo()
with self.assertRaises(TypeError):
woohoo(3, 5)
with self.assertRaises(TypeError):
woohoo(b=3)

def test_recursive(self):
depth = 0
@contextmanager
def woohoo():
nonlocal depth
before = depth
depth += 1
yield
depth -= 1
self.assertEqual(depth, before)

@woohoo()
def recursive():
if depth < 10:
recursive()

recursive()
self.assertEqual(depth, 0)


class ClosingTestCase(unittest.TestCase):

Expand Down