-
-
Save alecordev/b2e2466293cccfc956d8861e965519c9 to your computer and use it in GitHub Desktop.
Decorator and Context Manager simple examples
This file contains 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
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() |
This file contains 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
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