Created
October 30, 2014 14:28
-
-
Save wenhoujx/24a598a7c1abab3d2b29 to your computer and use it in GitHub Desktop.
decorator and pickle and wraps
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
from functools import wraps | |
import pickle | |
import sys | |
def logged(func): | |
""" | |
if not wrapped, the decoreated function has the same name as the original | |
cannot pickle | |
""" | |
# @wraps(func) | |
def with_logging(*args, **kwargs): | |
print func.__name__ + " was called" | |
return func(*args, **kwargs) | |
return with_logging | |
def f(x): | |
"""does some math | |
""" | |
return x**2 | |
if __name__ == '__main__': | |
try: | |
c = int(raw_input("input 1,2,3: ")) | |
except ValueError: | |
print 'not an int' | |
if c == 1: | |
""" | |
this doesn't work because the name conflict | |
""" | |
print 'test1' | |
""" | |
note this is equivalent to decoration syntax: | |
@logged | |
def f(x) .... | |
""" | |
f = logged(f) | |
print f(2) | |
# name is with_logging, lose of function information | |
print f.__name__ | |
with open('./delme', 'w') as ff: | |
pickle.dump(f, ff) | |
elif c == 2: | |
""" | |
this works, the returned fucntion name has to match __name__ | |
which is 'with_logging' in our case, this is a huge limitation. | |
for example, in debugging | |
""" | |
print 'test2' | |
with_logging = logged(f) | |
print with_logging(2) | |
# name is with_logging, lose of function information | |
print with_logging.__name__ | |
with open('./delme', 'w') as ff: | |
pickle.dump(with_logging, ff) | |
elif c == 3: | |
""" | |
wraps() is also a decorator that updates the function information | |
such as names .... | |
it takes a function as a parameter | |
using wraps() is equivalent to | |
@wraps(func) | |
def with_logging( ... | |
""" | |
# this works | |
print 'test3' | |
f = wraps(f)(logged(f)) | |
print f(2) | |
# no lose of function information | |
print f.__name__ | |
with open('./delme', 'w') as ff: | |
pickle.dump(f, ff) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment