Skip to content

Instantly share code, notes, and snippets.

@walkerh
Created January 21, 2019 01:59
Show Gist options
  • Save walkerh/b7e3b2ef3727786e63cf27abf22c1736 to your computer and use it in GitHub Desktop.
Save walkerh/b7e3b2ef3727786e63cf27abf22c1736 to your computer and use it in GitHub Desktop.
Context manager demo in Python 3.7
# Using this bash function (for color):
# color()(set -o pipefail;"$@" 2>&1>&3|sed $'s,.*,\e[31m&\e[m,'>&2)3>&1
# repeat each section by pasting after this:
# color python; echo $?
#
# Notice how ctx1 never does the correct cleanup by printing "exiting".
# Defining a context manager class.
class CTX:
def __init__(self, val):
self.val = val
def __enter__(self):
return self.val
def __exit__(self, *args):
print(args)
print('exiting', self.val)
with CTX(50) as v:
print('using', v)
exit(f'finished {v}')
# Using contextlib the wrong way.
from contextlib import contextmanager
@contextmanager
def ctx1(var):
yield var
print('exiting', var)
with ctx1(50) as v:
print('using', v)
exit(f'finished {v}')
# Using contextlib the right way.
from contextlib import contextmanager
@contextmanager
def ctx2(var):
try:
yield var
finally:
print('exiting', var)
with ctx2(50) as v:
print('using', v)
raise SystemExit(f'finished {v}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment