Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created October 21, 2020 16:07
Show Gist options
  • Save jaraco/cc65e349c609887587a9bcc008ee41f4 to your computer and use it in GitHub Desktop.
Save jaraco/cc65e349c609887587a9bcc008ee41f4 to your computer and use it in GitHub Desktop.
import gc
import random
import functools
import contextlib
class Opener:
@contextlib.contextmanager
def open(self):
yield random.randint(1, 100)
@functools.singledispatch
@contextlib.contextmanager
def make_context(obj):
with obj.open() as val:
del obj
yield val
def test_referrers():
opener = Opener()
assert len(gc.get_referrers(opener)) == 0
with make_context(opener) as val:
assert len(gc.get_referrers(opener)) == 0
del opener
assert isinstance(val, int)
__name__ == '__main__' and test_referrers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment