Last active
October 29, 2016 18:53
-
-
Save knowsuchagency/2eb8e55c95a3ff686e266fab7e125327 to your computer and use it in GitHub Desktop.
decorators example
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
import json | |
def introspect(func): | |
def inner(*args, **kwargs): | |
result = func(*args, **kwargs) | |
print('name:', func.__name__) | |
print('doc:', func.__doc__) | |
print('args:', args) | |
return result | |
return inner | |
def jsonify(func): | |
def inner(*args, **kwargs): | |
return json.dumps(func(*args, **kwargs)) | |
return inner | |
@jsonify | |
@introspect | |
def foo(*args): | |
""" | |
return args | |
:param args: | |
:return: | |
""" | |
return args | |
print(foo('hello', 'world')) | |
# class exercise | |
from functools import partial | |
import getpass | |
def decorator(f): | |
print_ = partial(print) | |
def inner(*args, **kwargs): | |
args = [getpass.getuser()] + [arg[:100] for arg in args] | |
with open('/tmp/log', 'a') as log: | |
p = partial(print_, file=log) | |
p(*args, **kwargs) | |
return inner | |
@decorator | |
def print(*args, **kwargs): | |
return None | |
print('hello', 'world') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment