Created
October 30, 2014 14:28
-
-
Save wenhoujx/dbf1caa552326992dcf5 to your computer and use it in GitHub Desktop.
decorator and pickle and wraps
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
1 from functools import wraps | |
2 import pickle | |
3 import sys | |
4 | |
5 | |
6 def logged(func): | |
7 """ | |
8 if not wrapped, the decoreated function has the same name as the original | |
9 cannot pickle | |
10 """ | |
11 # @wraps(func) | |
12 def with_logging(*args, **kwargs): | |
13 print func.__name__ + " was called" | |
14 return func(*args, **kwargs) | |
15 return with_logging | |
16 | |
17 | |
18 def f(x): | |
19 """does some math | |
20 """ | |
21 return x**2 | |
22 | |
23 if __name__ == '__main__': | |
24 try: | |
25 c = int(raw_input("input 1,2,3: ")) | |
26 except ValueError: | |
27 print 'not an int' | |
28 | |
29 if c == 1: | |
30 """ | |
31 this doesn't work because the name conflict | |
32 """ | |
33 print 'test1' | |
34 """ | |
35 note this is equivalent to decoration syntax: | |
36 @logged | |
37 def f(x) .... | |
38 """ | |
39 f = logged(f) | |
40 print f(2) | |
41 # name is with_logging, lose of function information | |
42 print f.__name__ | |
43 | |
44 with open('./delme', 'w') as ff: | |
45 pickle.dump(f, ff) | |
46 elif c == 2: | |
47 """ | |
48 this works, the returned fucntion name has to match __name__ | |
49 which is 'with_logging' in our case, this is a huge limitation. | |
50 for example, in debugging | |
51 """ | |
52 print 'test2' | |
53 with_logging = logged(f) | |
54 print with_logging(2) | |
55 # name is with_logging, lose of function information | |
56 print with_logging.__name__ | |
57 | |
58 with open('./delme', 'w') as ff: | |
59 pickle.dump(with_logging, ff) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment