Last active
July 29, 2019 01:20
-
-
Save estysdesu/859acd1f0dc58ea764babe0b04c71206 to your computer and use it in GitHub Desktop.
[Python: `with` context manager] #with #python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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