Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 29, 2019 01:20
Show Gist options
  • Save estysdesu/859acd1f0dc58ea764babe0b04c71206 to your computer and use it in GitHub Desktop.
Save estysdesu/859acd1f0dc58ea764babe0b04c71206 to your computer and use it in GitHub Desktop.
[Python: `with` context manager] #with #python
# https://effbot.org/zone/python-with-statement.htm
class Tyler():
def __enter__(self):
# <set-up>
# return <something> # essentially "with this state thats returned, do something"
def __exit__(self):
# <tear-down>
with Tyler() as ty:
# <do-something-with-ty>
##### SAME THING #####
# https://docs.python-guide.org/writing/structure/
from contextlib import contextmanager
@contextmanager
def custom_open(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with custom_open('file') as f:
contents = f.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment