Skip to content

Instantly share code, notes, and snippets.

@alecordev
Last active April 27, 2018 11:17
Show Gist options
  • Save alecordev/b2e2466293cccfc956d8861e965519c9 to your computer and use it in GitHub Desktop.
Save alecordev/b2e2466293cccfc956d8861e965519c9 to your computer and use it in GitHub Desktop.
Decorator and Context Manager simple examples
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
print('Wrapping')
return f(*args, **kwargs)
return wrapper
@decorator
def f():
print('Function f')
@contextlib.contextmanager
def f2():
print('Init')
yield
print('Finish')
from contextlib import contextmanager
@contextmanager
def db_transaction(connection):
cursor = connection.cursor()
try:
yield cursor
except:
connection.rollback()
raise
else:
connection.commit()
class FileContext:
def __init__(self, f):
self.file = open(f)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
print(traceback)
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
yield f
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment