python custom context
To write your own version of
with open('tim.txt','r') as data_file: bla bla bla
You use the enter and exit methods specifically like this.
class CustomOpen(object): def __init__(self, filename): self.file = open(filename) def __enter__(self): return self.file def __exit__(self, ctx_type, ctx_value, ctx_traceback): self.file.close() with CustomOpen('file') as f: contents = f.read()
For those people who are now feeling clever, this can be written as
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()
Which is shorter but not OO.