-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecorators.py
More file actions
2368 lines (1704 loc) · 67.9 KB
/
Decorators.py
File metadata and controls
2368 lines (1704 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#装饰器函数与装饰器类" data-toc-modified-id="装饰器函数与装饰器类-1"><span class="toc-item-num">1 </span>装饰器函数与装饰器类</a></span><ul class="toc-item"><li><span><a href="#装饰器函数" data-toc-modified-id="装饰器函数-1.1"><span class="toc-item-num">1.1 </span>装饰器函数</a></span></li><li><span><a href="#装饰器类" data-toc-modified-id="装饰器类-1.2"><span class="toc-item-num">1.2 </span>装饰器类</a></span></li></ul></li><li><span><a href="#使用装饰器的例子" data-toc-modified-id="使用装饰器的例子-2"><span class="toc-item-num">2 </span>使用装饰器的例子</a></span><ul class="toc-item"><li><span><a href="#classmethod" data-toc-modified-id="classmethod-2.1"><span class="toc-item-num">2.1 </span>classmethod</a></span></li><li><span><a href="#staticmethod" data-toc-modified-id="staticmethod-2.2"><span class="toc-item-num">2.2 </span>staticmethod</a></span></li><li><span><a href="#property" data-toc-modified-id="property-2.3"><span class="toc-item-num">2.3 </span>property</a></span></li><li><span><a href="#deprecation-of-function" data-toc-modified-id="deprecation-of-function-2.4"><span class="toc-item-num">2.4 </span>deprecation of function</a></span></li><li><span><a href="#WHILE-loop-removing-decorator" data-toc-modified-id="WHILE-loop-removing-decorator-2.5"><span class="toc-item-num">2.5 </span>WHILE-loop removing decorator</a></span></li><li><span><a href="#plugin-registration-system" data-toc-modified-id="plugin-registration-system-2.6"><span class="toc-item-num">2.6 </span>plugin registration system</a></span></li></ul></li><li><span><a href="#摘自-https://wiki.python.org/moin/PythonDecoratorLibrary" data-toc-modified-id="摘自-https://wiki.python.org/moin/PythonDecoratorLibrary-3"><span class="toc-item-num">3 </span>摘自 <a href="https://wiki.python.org/moin/PythonDecoratorLibrary" target="_blank">https://wiki.python.org/moin/PythonDecoratorLibrary</a></a></span><ul class="toc-item"><li><span><a href="#不使用-@wraps来保持原始函数的信息" data-toc-modified-id="不使用-@wraps来保持原始函数的信息-3.1"><span class="toc-item-num">3.1 </span>不使用 @wraps来保持原始函数的信息</a></span></li><li><span><a href="#利用装饰器定义属性" data-toc-modified-id="利用装饰器定义属性-3.2"><span class="toc-item-num">3.2 </span>利用装饰器定义属性</a></span></li><li><span><a href="#Memorize" data-toc-modified-id="Memorize-3.3"><span class="toc-item-num">3.3 </span>Memorize</a></span></li><li><span><a href="#Alternate-memoize-as-nested-functions" data-toc-modified-id="Alternate-memoize-as-nested-functions-3.4"><span class="toc-item-num">3.4 </span>Alternate memoize as nested functions</a></span></li><li><span><a href="#Alternate-memoize-as-dict-subclass" data-toc-modified-id="Alternate-memoize-as-dict-subclass-3.5"><span class="toc-item-num">3.5 </span>Alternate memoize as dict subclass</a></span></li><li><span><a href="#Alternate-memoize-that-stores-cache-between-executions" data-toc-modified-id="Alternate-memoize-that-stores-cache-between-executions-3.6"><span class="toc-item-num">3.6 </span>Alternate memoize that stores cache between executions</a></span></li><li><span><a href="#Cached-Properties" data-toc-modified-id="Cached-Properties-3.7"><span class="toc-item-num">3.7 </span>Cached Properties</a></span></li><li><span><a href="#Retry" data-toc-modified-id="Retry-3.8"><span class="toc-item-num">3.8 </span>Retry</a></span></li><li><span><a href="#Pseudo-curring" data-toc-modified-id="Pseudo-curring-3.9"><span class="toc-item-num">3.9 </span>Pseudo-curring</a></span></li><li><span><a href="#Creating-decorator-with-optional-argument" data-toc-modified-id="Creating-decorator-with-optional-argument-3.10"><span class="toc-item-num">3.10 </span>Creating decorator with optional argument</a></span></li><li><span><a href="#Controllable-DIY-debug" data-toc-modified-id="Controllable-DIY-debug-3.11"><span class="toc-item-num">3.11 </span>Controllable DIY debug</a></span></li><li><span><a href="#Easy-adding-methods-to-a-class-instance" data-toc-modified-id="Easy-adding-methods-to-a-class-instance-3.12"><span class="toc-item-num">3.12 </span>Easy adding methods to a class instance</a></span></li><li><span><a href="#Counting-function-calls" data-toc-modified-id="Counting-function-calls-3.13"><span class="toc-item-num">3.13 </span>Counting function calls</a></span></li><li><span><a href="#Alternate-counting-function-calls" data-toc-modified-id="Alternate-counting-function-calls-3.14"><span class="toc-item-num">3.14 </span>Alternate counting function calls</a></span></li><li><span><a href="#Generating-Deprecation-Warnings" data-toc-modified-id="Generating-Deprecation-Warnings-3.15"><span class="toc-item-num">3.15 </span>Generating Deprecation Warnings</a></span></li><li><span><a href="#Smart-deprecation-warnings(with-valid-filenames,-line-number,-etc)" data-toc-modified-id="Smart-deprecation-warnings(with-valid-filenames,-line-number,-etc)-3.16"><span class="toc-item-num">3.16 </span>Smart deprecation warnings(with valid filenames, line number, etc)</a></span></li><li><span><a href="#Ignoring-Deprecation-Warning" data-toc-modified-id="Ignoring-Deprecation-Warning-3.17"><span class="toc-item-num">3.17 </span>Ignoring Deprecation Warning</a></span></li><li><span><a href="#Enable/Disable-Decorators" data-toc-modified-id="Enable/Disable-Decorators-3.18"><span class="toc-item-num">3.18 </span>Enable/Disable Decorators</a></span></li><li><span><a href="#Easy-Dump-of-Function-Arguments" data-toc-modified-id="Easy-Dump-of-Function-Arguments-3.19"><span class="toc-item-num">3.19 </span>Easy Dump of Function Arguments</a></span></li><li><span><a href="#Pre-/Post--Conditions" data-toc-modified-id="Pre-/Post--Conditions-3.20"><span class="toc-item-num">3.20 </span>Pre-/Post- Conditions</a></span></li><li><span><a href="#Profiling/Coverage-Analysis" data-toc-modified-id="Profiling/Coverage-Analysis-3.21"><span class="toc-item-num">3.21 </span>Profiling/Coverage Analysis</a></span></li><li><span><a href="#Line-Tracing-Individual-Functions" data-toc-modified-id="Line-Tracing-Individual-Functions-3.22"><span class="toc-item-num">3.22 </span>Line Tracing Individual Functions</a></span></li><li><span><a href="#Synchronization" data-toc-modified-id="Synchronization-3.23"><span class="toc-item-num">3.23 </span>Synchronization</a></span></li><li><span><a href="#Type-Enforcement-(accepts/returns)" data-toc-modified-id="Type-Enforcement-(accepts/returns)-3.24"><span class="toc-item-num">3.24 </span>Type Enforcement (accepts/returns)</a></span></li><li><span><a href="#CGI-method-wrapper(略)" data-toc-modified-id="CGI-method-wrapper(略)-3.25"><span class="toc-item-num">3.25 </span>CGI method wrapper(略)</a></span></li><li><span><a href="#State-Machine-Implementation" data-toc-modified-id="State-Machine-Implementation-3.26"><span class="toc-item-num">3.26 </span>State Machine Implementation</a></span></li><li><span><a href="#C++/Java-keyword-like-function-decorators(略)" data-toc-modified-id="C++/Java-keyword-like-function-decorators(略)-3.27"><span class="toc-item-num">3.27 </span>C++/Java-keyword-like function decorators(略)</a></span></li><li><span><a href="#Different-Decorator-Forms" data-toc-modified-id="Different-Decorator-Forms-3.28"><span class="toc-item-num">3.28 </span>Different Decorator Forms</a></span></li><li><span><a href="#Unimplemented-function-replacement(略)" data-toc-modified-id="Unimplemented-function-replacement(略)-3.29"><span class="toc-item-num">3.29 </span>Unimplemented function replacement(略)</a></span></li><li><span><a href="#Redirects-stdout-printing-to-python-standard-logging" data-toc-modified-id="Redirects-stdout-printing-to-python-standard-logging-3.30"><span class="toc-item-num">3.30 </span>Redirects stdout printing to python standard logging</a></span></li><li><span><a href="#Access-Control" data-toc-modified-id="Access-Control-3.31"><span class="toc-item-num">3.31 </span>Access Control</a></span></li><li><span><a href="#Events-rising-and-handling(略)" data-toc-modified-id="Events-rising-and-handling(略)-3.32"><span class="toc-item-num">3.32 </span>Events rising and handling(略)</a></span></li><li><span><a href="#Singleton" data-toc-modified-id="Singleton-3.33"><span class="toc-item-num">3.33 </span>Singleton</a></span></li><li><span><a href="#Asynchronous-Call" data-toc-modified-id="Asynchronous-Call-3.34"><span class="toc-item-num">3.34 </span>Asynchronous Call</a></span></li><li><span><a href="#Class-method-decorator-using-instance(???)" data-toc-modified-id="Class-method-decorator-using-instance(???)-3.35"><span class="toc-item-num">3.35 </span>Class method decorator using instance(???)</a></span></li></ul></li></ul></div>
# ##### 装饰器函数与装饰器类
# ###### 装饰器函数
# 简单装饰器, 返回原来的函数
# In[2]:
def simple_decorator(func):
print('Doing decoration')
return func
#装饰器在定义函数的时候就
#已经执行了, 因此可以被用来
#在内部函数执行前后做一些
#额外的工作
@simple_decorator
def func():
print('Inside function.')
# 带参数的装饰器, 返回原来的函数
# In[3]:
def decorator_with_args(arg):
print('defining the decorator.')
def _decorator(func):
#内部函数中 args仍然可见
print('doing decoration, %r' % arg)
return func
return _decorator
@decorator_with_args('abc')
def func():
print('Inside function.')
# 简单装饰器, 返回新的函数 _wrapper
# In[47]:
def simple_decorator(func):
print('Defining the decorator.')
def _wrapper(*args, **kwargs):
print("Inside wrapper, %r %r" % (args, kwargs))
return func(*args, **kwargs)
return _wrapper
@simple_decorator
def func(*args, **kwargs):
print('Inside function, %r %r' % (args, kwargs))
return 14
# 带参数的装饰器, 返回新的函数 \_wrapper
# In[4]:
def decorator_with_args(arg):
print('Defining the decorator.')
def _decorator(func):
print("Doing decoration, %r" % arg)
def _wrapper(*args, **kwargs):
print("Inside wrapper, %r %r" % (args, kwargs))
return func(*args, **kwargs)
print("Finish decoration, %r" % arg)
return _wrapper
print('Finish the decorator.')
return _decorator
@decorator_with_args('abc')
def func(*args, **kwargs):
print('Inside function, %r %r' % (args, kwargs))
return 14
# ###### 装饰器类
# 返回原始函数的装饰器类
# In[5]:
class decorator_class(object):
def __init__(self, arg):
print("In decorator init, %s"% arg)
self.arg = arg
def __call__(self, func):
print('In decorator call, %s' % self.arg)
return func
deco_instance = decorator_class(arg = 'foo')
@deco_instance
def function(*args, **kwargs):
print('In function, %s %s' % (args, kwargs))
# **返回新对象的装饰器类**
# In[8]:
class replacing_decorator_class(object):
def __init__(self, arg):
print('In decorator init, %s' % arg)
self.arg = arg
def __call__(self, func):
print('In decorator call, %s' % self.arg)
self.func = func
return self._wrapper
def _wrapper(self, *args, **kwargs):
print('In the wrapper, %s %s' % (args, kwargs))
return self.func(*args, **kwargs)
#初始化函数在类的实例化时运行
deco_instance = replacing_decorator_class(arg = 'foo')
#__call__函数在装饰器装配时运行,
#同时初始化func成员
#然后返回wrapper, 一个新的对象。
@deco_instance
def func(*args, **kwargs):
print('In function, %s %s' % (args, kwargs))
#在wrapper方法中运行func
func(0,1, a = 3)
# 注意上面的 replacing_decorator_class 会返回 \_wrapper成员.<br>
# 这么做的一个弊端是: 原始函数 func的名字, doc, 参数列表全部丢失.<br>
# **解决方案: functools.update_wrapper 或 functools.wraps**
# In[14]:
from functools import update_wrapper, wraps
#functools.update_wrapper
def replacing_decorator_with_args(arg):
print('defining the decorator')
def _decorator(function):
print('doing decoration, %r' % arg)
def _wrapper(*args, **kwargs):
print('inside wrapper, %r %r' % (args, kwargs))
return function(*args, **kwargs)
return update_wrapper(_wrapper, function)
return _decorator
@replacing_decorator_with_args('abc')
def function(a = 13):
"""
extensive documentation
"""
print('inside function')
return 14
#原始函数的名字和doc都可以拷贝过来
print(function.__name__, function.__doc__)
#但是参数列表依然无法copy
function.__code__.co_varnames
# In[16]:
#functools.wraps
def replacing_decorator_with_args(arg):
print('defining the decorator')
def _decorator(function):
print('doing decoration, %r' % arg)
@wraps(function)
def _wrapper(*args, **kwargs):
print('inside wrapper, %r %r' % (args, kwargs))
return function(*args, **kwargs)
return _wrapper
return _decorator
@replacing_decorator_with_args('abc')
def function(a = 13):
"""
extensive documentation
"""
print('inside function')
return 14
#原始函数的名字和doc都可以拷贝过来
print(function.__name__, function.__doc__)
#同上, 参数列表无法被copy
function.__code__.co_varnames
# ##### 使用装饰器的例子
# ###### classmethod
# In[17]:
import numpy as np
class Array(object):
def __init__(self, data):
self.data = data
#classmethod作为工厂方法, 创建类的实例
@classmethod
def fromfile(cls, file):
data = np.load(file)
return cls(data)
# ###### staticmethod
# In[23]:
#在开发中,我们常常需要定义一些方法,这些方法跟类有关,但在实现时并不需要引用类或者实例,
#例如,设置环境变量,修改另一个类的变量,等。这个时候,我们可以使用静态方法。
# ###### property
# 注意只实现了property的属性是 read-only的
# In[21]:
class A(object):
@property
def a(self):
"""an important attribute
"""
return 'a value'
print(A().a)
try:
A().a = 3
except AttributeError:
print('没有实现setter方法.')
# 你可以实现setter方法, 让它可以被赋值
# In[22]:
class Rectangle(object):
def __init__(self, edge):
self.edge = edge
@property
def area(self):
return self.edge **2
@area.setter
def area(self, area):
self.edge = area ** .5
# ###### deprecation of function
# In[29]:
#我们要在某个函数第一次调用时打出 deprecation警告
class deprecated(object):
def __call__(self, func):
self.func = func
self.count = 0
return self._wrapper
def _wrapper(self, *args, **kwrags):
self.count += 1
if self.count == 1:
print(self.func.__name__, 'is deprecated')
return self.func(*args, **kwargs)
#你也可以用装饰器函数
def deprecated(func):
count = [0]
def wrapper(*args, **kwargs):
count[0] += 1
if count[0] == 1:
print(func.__name__, 'is deprecated')
return func(*args, **kwargs)
return wrapper
# ###### WHILE-loop removing decorator
# In[23]:
#当然你也可以直接用 yield, 但是某些情况下 list(EXPR) 会比较丑
def vectorized(gen_func):
"""
Parameters
----------
gen_func: 生成器函数
"""
def wrapper(*args, **kwargs):
return list(gen_func(*args, **kwargs))
return update_wrapper(wrapper, gen_func)
@vectorized
def find_answers():
while True:
ans = look_for_next_answer()
if ans is None:
break
yield ans
# ###### plugin registration system
# In[ ]:
#WordProcessor装饰器类不会更改他装饰的类, 而是把他加到PLUGINS中去
class WordProcessor(object):
PLUGINS = []
#process方法实例化PLUGINS中的类,然后执行他们
def process(self, text):
for plugin in self.PLUGINS:
text = plugin().cleanup(text)
return text
@classmethod
def plugin(cls, plugin):
cls.PLUGINS.append(plugin)
@WordProcessor.plugin
class CleanMdashesExtension(object):
def cleanup(self, text):
return text.replace('&mdash', u'\N{em dash}')
# ##### 摘自 https://wiki.python.org/moin/PythonDecoratorLibrary
# ###### 不使用 @wraps来保持原始函数的信息
# In[41]:
def simple_decorator(decorator):
"""
你的装饰器函数 `decorator`必须足够简单:
1. 接受一个函数, 返回一个函数
2. 不修改函数的属性和文档
"""
def new_decorator(f):
g = decorator(f)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
g.__dict__.update(f.__dict__)
return g
# 下面要修改 new_decorator, 使得它和原装饰器函数一致
# print(new_decorator.__name__)
new_decorator.__name__ = decorator.__name__
# print(new_decorator.__name__)
new_decorator.__doc__ = decorator.__doc__
new_decorator.__dict__.update(decorator.__dict__)
return new_decorator
def demo_logging_decorator(func):
def wrapper(*args, **kwargs):
print('calling {}'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
@simple_decorator
def better_demo_logging_decorator(func):
def wrapper(*args, **kwargs):
print('calling {}'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
def add(x, y):
'两数相加'
return x + y
@demo_logging_decorator
def add_with_log(x, y):
'两数相加'
return x + y
@better_demo_logging_decorator
def add_with_log_v2(x, y):
'两数相加'
return x + y
print('装饰之前:')
print(add.__name__)
print(add.__doc__)
print(add.__dict__)
print('使用了 demo_logging_decorator:')
print(add_with_log.__name__)
print(add_with_log.__doc__)
print(add_with_log.__dict__)
print('使用了 better_demo_logging_decorator:')
print(add_with_log_v2.__name__)
print(add_with_log_v2.__doc__)
print(add_with_log_v2.__dict__)
# ###### 利用装饰器定义属性
# In[3]:
import sys
def test(a, b):
#获取当前函数的局部变量
print(sys._getframe(0).f_locals)
#获取main的全部变量, 这里面包括:
#1. 导入的模块
#2. 用户定义的函数(def)
print(sys._getframe(1).f_locals.keys())
# test(1, 3)
# In[9]:
import sys
def proget(func):
locals_ = sys._getframe(1).f_locals
print('\nIn proget:')
print('locals: ', locals_)
name = func.__name__
prop = locals_.get(name)
print('before set property: ', prop)
if not isinstance(prop, property):
prop = property(fget=func, doc=func.__doc__)
else:
doc = prop.__doc__ or func.__doc__
prop = property(func, prop.fset, prop.fdel, doc)
print('after set property: ', prop)
return prop
def propset(func):
locals_ = sys._getframe(1).f_locals
print('\nIn proset:')
print('locals: ', locals_)
name = func.__name__
prop = locals_.get(name)
print('before set property: ', prop)
if not isinstance(prop, property):
prop = property(None, func, doc=func.__doc__)
else:
doc = prop.__doc__ or func.__doc__
prop = property(prop.fget, func, prop.fdel, doc)
print('after set property: ', prop)
return prop
# In[10]:
#This canbe used like this.
class Example(object):
@proget
def myattr(self):
return self._half * 2
@propset
def myattr(self, value):
self._half = value / 2
# 也可以不用生成器--灵活运用 locals()
# In[11]:
class Example(object):
def myattr():
doc = """This is the doc string."""
def fget(self):
return self._half / 2
def fset(self, value):
self._half = value
def fdel(self):
del self._half
return property(**locals())
myattr = myattr()
# In[12]:
Example.__dict__
# 另一个装饰器的实现
# In[ ]:
# ###### Memorize
# In[19]:
import collections
import functools
class memorized(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance
# better to not cache than blow up
return self.func(*args)
if args in self.cache:
print(f'{args} in cache.')
return self.cache[args]
else:
print(f'{args} cached.')
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
"""Return the function's docstring"""
return self.func.__doc__
def __get__(self, instance, owner):
print('calling __get__.')
return functools.partial(self.__call__, instance)
# In[20]:
@memorized
def fib(n):
if n in (0,1):
return n
return fib(n-1) + fib(n-2)
# In[21]:
print(fib(12))
# ###### Alternate memoize as nested functions
# In[22]:
def memorized(obj):
cache = {}
obj.cache = {}
@functools.warps(obj)
def memorizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memorizer
# ###### Alternate memoize as dict subclass
# In[23]:
class memorize(dict):
"""
memorize 继承了字典类
"""
def __init__(self, func):
self.func = func
def __call__(self, *args):
return self[args]
def __missing__(self, key):
result = self[key] = self.func(*key)
return result
# ###### Alternate memoize that stores cache between executions
# In[54]:
import sys
import inspect
def func(a, b):
"""
stack的最顶层, 即idx为零的元素, 储存了最近执行的那一行
"""
frame = inspect.stack()
# `frame = inspect.stack()`处的栈帧信息
print(frame[0])
print(sys._getframe(0))
# `def func(a, b)`处的栈帧信息
print(frame[1])
print(sys._getframe(1))
# func所在文件的栈帧信息
print(frame[-1].filename)
# In[55]:
func(1, 3)
# In[5]:
import pickle
import collections
import functools
import inspect
import os.path
import re
import unicodedata
class Memorize(object):
def __init__(self, func):
self.func = func
self._set_parent_filename()
self.__name__ = self.func.__name__
self._set_cache_filename()
if self.cache_exists():
self.read_cache()
if not self.is_safe_cache():
self.cache = {}
else:
self.cache = {}
def __call__(self, *args):
print('Call __call__ of Memorize.')
if not isinstance(args, collections.Hashable):
return self.func(*args)
if args in self.cache:
print('Find in cache.')
return self.cache[args]
else:
print('Update cache.')
value = self.func(*args)
self.cache[args] = value
self.save_cache()
return value
#在初始化的时候被调用
def _set_parent_filename(self):
"""Set `self.parent_file` to the absolute path
of the file containing the memorized function.
"""
def filename_from_path(filepath):
return filepath.split('/')[-1]
print('Setting parent filename.')
real_parent_file = inspect.stack()[-1].filename
print('real_parent_file is: ', real_parent_file)
self.parent_filepath = os.path.abspath(real_parent_file)
print('parent_filepath is: ', self.parent_filepath)
self.parent_filename = filename_from_path(real_parent_file)
#在初始化的时候被调用
def _set_cache_filename(self):
"""Set self.cache_filename to an os-compliant
version of `file_function.cache`
"""
def slugfy(value):
"""Normalizes string, convert to lowercase, removes
non-alpha characters, and converts space to hyphens
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = re.sub(r'[^\w\s-]', '', value.decode('utf-8', 'ignore'))
value = value.strip().lower()
value = re.sub(r'[-\s]+', '-', value)
return value
filename = slugfy(self.parent_filename.replace('.py', ''))
print('The filename is: ', filename)
funcname = slugfy(self.__name__)
self.cache_filename = filename + '_' + funcname + '.cache'
print('The file is in:', self.cache_filename)
#在is_safe_cache里被调用
def get_last_update(self):
"""Return the time that the parent file was last
update
"""
#获取文件被更改的次数
last_update_time = os.path.getmtime(self.parent_filepath)
return last_update_time
# 在初始化的时候被调用
def is_safe_cache(self):
"""Returns True if the file containing the memorized
function has not been updated since the cache was
last saved.
"""
if self.get_last_update() > self.timestamp:
return False
else:
return True
# 在初始化的时候调用
def read_cache(self):
"""
Read a picked dictionary into self.timestamp and self.cache
"""
with open(self.cache_filename, 'rb') as f:
data = pickle.loads(f.read())
self.timestamp = data['timestamp']
self.cache = data['cache']
# 在碰到没有出现过的参数的时候调用
def save_cache(self):
"""Pickle the file's timestamp and function's cache
in a dict object
"""
with open(self.cache_filename, 'wb+') as f:
out = dict()
out['timestamp'] = self.get_last_update()
out['cache'] = self.cache
f.write(pickle.dumps(out))
# 在初始化的时候调用
def cache_exists(self):
"""Returns True if a matching cache exists in the current directory
"""
if os.path.isfile(self.cache_filename):
return True
return False
def __repr__(self):
"""Return the function's docstring
"""
return self.func.__doc__
def __get__(self, instance, owner):
"""Support instance methods
"""
return functools.partial(self.__call__, instance)
# In[6]:
@Memorize
def f(a, b):
return a+b
# In[7]:
f(1, 2)
# In[8]:
f(2, 4)
# In[9]:
f(1, 2)
# ###### Cached Properties
# In[26]:
import time
import random
class cached_property(object):
"""Decorator for read-only `properties` evaluated only once within TTL period.
"""
def __init__(self, ttl=300):
self.ttl = ttl
#在定义 property.get的时候调用
def __call__(self, func, doc=None):
print('Call __call__.')
self.func = func
print(type(func))
self.__doc__ = doc or func.__doc__
self.__name__ = func.__name__
self.__module__ = func.__module__
return self
def __get__(self, instance, owner):
now = time.time()
try:
value, last_update = instance._cache[self.__name__]
if self.ttl > 0 and now - last_update > self.ttl: #recache
print('Need recache.')
raise AttributeError
except (KeyError, AttributeError):
value = self.func(instance) #调用实例的方法
try:
cache = instance._cache
except AttributeError:
cache = instance._cache = {}
cache[self.__name__] = (value, now)
return value
# In[27]:
class MyClass(object):
# create property whose value is cached for ten minutes
@cached_property(ttl=600)
def randint(self):
# will only be evaluated every 10 min. at maximum.
return random.randint(0, 100)
# In[28]:
a = MyClass()
a.randint
# ###### Retry
# In[2]:
import time
import math
def retry(tries, delay=3, backoff=2):
"""Retry a function or method until it returns True.
"""
if backoff <= 1:
raise ValueError('backoff must be greater than 1.')
tries = math.floor(tries)
if tries < 0:
raise ValueError('tries must be 0 or greater.')
if delay <= 0:
raise ValueError('delay must be greater than 0.')
def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
rv = f(*args, **kwargs)
while mtries >0:
if rv is True:
return True
mtries -= 1
# wait
time.sleep(mdelay)
# make future wait longer
mdelay *= backoff
# try again
rv = f(*args, **kwargs)
return False
return f_retry # true decorator -> decorated function
return deco_retry # @retry(arg[, ...]) -> true decorator
# ###### Pseudo-curring
# In[4]:
class curried(object):
"""Decorator that return a function that keeps returning
functions until all arguments are supplied; then the orginal
function is evaluated.
"""
def __init__(self, func, *args):
self.func = args
self.args = args
def __call__(self, *args):
args_ = self.args + args
# 如果 当前的非关键字参数 少于func中的关键字参数
# 就 递归地 return 一个 curried 对象
if len(args_) < self.func.__code__.co_argcount:
return curried(self.func, *args)
else:
return self.func(*args)
# ###### Creating decorator with optional argument
# In[15]:
import functools, inspect
def decorator(func):
"""Allow to use decorator either with arguments or not.
"""
def isFuncArg(*args, **kwargs):
"""判断参数是否只有一个, 且为(被装饰的)函数
"""
return len(args) == 1 and len(kwargs) == 0 and (inspect.isfunction(args[0]) or isinstance(args[0], type))
if isinstance(func, type):
def class_wrapper(*args, **kwargs):
if isFuncArg(*args, **kwargs):
return func()(*args, **kwargs) # create a cls before use
else:
return func(*args, **kwargs)
class_wrapper.__name__ = func.__name__
class_wrapper.__module__ = func.__module__
return class_wrapper
else:
print('被装饰的对象是函数.')
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
if isFuncArg(*args, **kwargs):
print('装饰了函数: ', (args, kwargs))
return func(*args, **kwargs)
else:
print('装饰了函数, 并且有参数: ', (args, kwargs))
def functor(userFunc):
print(userFunc)
return func(userFunc, *args, **kwargs)
return functor
return func_wrapper
# In[16]:
@decorator
def apply(func, *args, **kwargs):
"""执行被装饰的函数
"""
return func(*args, **kwargs)
# In[17]:
@apply
def test():
return 'test'
# In[18]:
@apply(2, 3)
def test(a, b):
return a + b
# ###### Controllable DIY debug
# In[27]:
import sys
WHAT_TO_DEBUG = set(['io', 'core']) # change to what you need
class debug(object):
"""Decorator which helps to control what aspects of program
to debug on per-function basis. Aspects are provided as list
of arguments. It DOSEN'T slowdown functions which aren't