-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathchapter7.py
More file actions
1335 lines (884 loc) · 34.8 KB
/
chapter7.py
File metadata and controls
1335 lines (884 loc) · 34.8 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
####################################################
## 7. Advanced language Features
####################################################
from __future__ import annotations
####################################################
## Index
####################################################
# 7.1 Additional types
# 7.2 Generators
# 7.3 Iterators
# 7.4 Semi-corroutines (Advanced Generators)
# 7.5 Corrutines (AsyncIO)
# 7.6 Decorators
# 7.7 Context Manager
# 7.8 Pearls of the Standard Library - Pathlib
# 7.9 Pearls of the Standard Library - Itertools
# 7.10 Pearls of the Standard Library - OS
# 7.11 Pearls of the Standard Library - Serialization
# 7.12 Pearls of the Standard Library - Emails
####################################################
## 7.1 Additional Types
####################################################
####################################################
## 7.1.1 NamedTuple and namedtuple
####################################################
## Reference: https://docs.python.org/3/library/collections.html#collections.namedtuple
from dataclasses import dataclass, astuple
from collections import namedtuple
@dataclass
class Vector:
x: float
y: float
def modulo(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
origin = Vector(0, 0)
origin.x # => 0
origin.y # => 0
print(origin) # => Vector(x=0, y=0)
# x, y = origin # => Error
x, y = astuple(origin) # => No Error
# origin[0] # => Error Cannot use indexes in classes
origin.x = 3 # => Default mutable attributes
origin.y = 4 # => Default mutable attributes
print(origin) # => Vector(x=3, y=4)
assert origin.modulo() == 5
# Using frozen=True
@dataclass(frozen=True)
class VectorImmutable:
x: float
y: float
def modulo(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
origin = VectorImmutable(0, 0)
origin.x # => 0
origin.y # => 0
print(origin) # => Vector(x=0, y=0)
# x, y = origin # => Error
x, y = astuple(origin) # => No Error
# origin[0] # => Error Cannot use indexes in classes
# origin.x = 3 # => Error attributes are immutable
# origin.y = 4 # => Error attributes are immutable
assert origin.modulo() == 0
# Using collections.namedtuple
VectorAlternate = namedtuple("VectorAlternate", ["x", "y"])
def modulo_without_types(vector: VectorAlternateVector) -> float:
return (vector.x**2 + vector.y**2) ** 0.5 # Warning for not knowing types.
point = VectorAlternate(3, 4)
point.x # => 3 with Warning: No type specified
point.y # => 4 with Warning: No type specified
print(point) # => VectorAlternate(x=3, y=4)
x, y = point # => x=3, y=4 with Warning: No type specified
# point.x = 1 # => Error
assert point[0] == 3
assert point[1] == 4
assert modulo_without_types(point) == 5
# Using NamedTuple as superclass
from typing import NamedTuple
class VectorAlternativeTyped(NamedTuple):
x: float
y: float
def modulo(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
def typed_modulo_1(vector: VectorAlternativeTyped) -> float:
return (vector.x**2 + vector.y**2) ** 0.5
typed_point_1_str = VectorAlternativeTyped("1", "1") # Warning String != Float
typed_point_1 = VectorAlternativeTyped(3, 4)
typed_point_1.x # => 3
typed_point_1.y # => 4
print(typed_point_1) # => VectorAlternativeTyped(x=3, y=4)
x, y = typed_point_1 # => x=3, y=4
# typed_point_1.x = 1 # => Error
assert typed_point_1[0] == 3
assert typed_point_1[1] == 4
assert typed_modulo_1(typed_point_1) == 5
# Using NamedTuple as a function
VectorAlternativeTyped_2 = NamedTuple(
"VectorAlternativeTyped_2", [("x", float), ("y", float)]
)
def typed_modulo_2(vector: VectorAlternativeTyped_2) -> float:
return (vector.x**2 + vector.y**2) ** 0.5
typed_point_2 = VectorAlternativeTyped_2(3, 4)
typed_point_2.x # => 1
typed_point_2.x # => 1
print(typed_point_2) # => VectorAlternate(x=1, y=1)
x, y = typed_point_2 # => x=1, y=1
# typed_point_2.x = 1 # => Error
assert typed_point_2[0] == 3
assert typed_point_2[1] == 4
assert typed_modulo_2(typed_point_2) == 5
####################################################
## 7.1.2 Counter
####################################################
# Reference: https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
# Excerpt from Moby-Dick by Herman Melville
# Source: https://www.gutenberg.org/files/2701/2701-h/2701-h.htm#link2HCH0001
text = """
Call me Ishmael. Some years ago—never mind how long precisely—having little or
no money in my purse, and nothing particular to interest me on shore, I thought
I would sail about a little and see the watery part of the world. It is a way I
have of driving off the spleen and regulating the circulation. Whenever I find
myself growing grim about the mouth; whenever it is a damp, drizzly November in
my soul; whenever I find myself involuntarily pausing before coffin warehouses,
and bringing up the rear of every funeral I meet; and especially whenever my
hypos get such an upper hand of me, that it requires a strong moral principle to
prevent me from deliberately stepping into the street, and methodically knocking
people’s hats off—then, I account it high time to get to sea as soon as I can.
This is my substitute for pistol and ball. With a philosophical flourish Cato
throws himself upon his sword; I quietly take to the ship. There is nothing
surprising in this. If they but knew it, almost all men in their degree, some
time or other, cherish very nearly the same feelings towards the ocean with me.
"""
letter_counter = Counter(text)
letter_counter.most_common(4) # => [(' ', 184), ('e', 107), ('t', 74), ('i', 68)]
word_counter = Counter(text.split())
word_counter.most_common(4) # => [('the', 10), ('I', 9), ('and', 7), ('to', 5)]
####################################################
## 7.1.3 Defaultdict
####################################################
# Reference: https://docs.python.org/3/library/collections.html#collections.defaultdict
from collections import defaultdict
student_grade: defaultdict[str, List[int]] = defaultdict(list)
student_grade["Peter"].append(8) # Does not throw KeyError
student_grade["Mary"].append(9)
student_grade["Peter"].append(3)
student_grade["Mary"].append(8)
student_grade["Peter"].append(7)
assert student_grade == {"Peter": [8, 3, 7], "Mary": [9, 8]}
####################################################
## 7.1.4 Enum
####################################################
# Reference: https://docs.python.org/3/library/enum.html
from enum import Enum, auto
class Permissions(Enum):
ADMIN = auto()
USER = auto()
EDITOR = auto()
@staticmethod
def has_access_control_panel_1(permission: Permissions) -> bool:
return permission is Permissions.ADMIN or permission is Permissions.EDITOR
Permissions.ADMIN # => Permissions.ADMIN
Permissions.ADMIN.value # => 1
Permissions['ADMIN'] # => Permissions.ADMIN
Permissions['ADMIN'].value # => 1
print(Permissions.__members__.keys()) # => ['ADMIN', 'USER', 'EDITOR']
print(Permissions.__members__.values()) # => [<Permissions.ADMIN: 1>, <Permissions.USER: 2>, <Permissions.EDITOR: 3>]
Permissions.has_access_control_panel_1("REDACTOR") # No Error - Warning Incompatible Type.
assert Permissions.has_access_control_panel_1(Permissions.ADMIN)
# Alternative using typing.Literal
from typing import Literal
PermissionsA = Literal["ADMIN", "EDITOR", "USER"]
class PermissionsAlternative:
@staticmethod
def has_access_control_panel_2(permission: PermissionsA) -> bool:
return permission in ["ADMIN", "EDITOR"]
PermissionsAlternative.has_access_control_panel_2("EDITOR") # No Error - Warning Type Incompatible
assert PermissionsAlternative.has_access_control_panel_2("ADMIN")
####################################################
## 7.1.4 SimpleNameSpace
####################################################
from dataclasses import dataclass
@dataclass
class Person:
name: str
employee_1 = Person("John")
employee_1.name # => John
# employee_1["name"] # => Error - Cannot use keys with dataclasses
employee_1.age = 24 # => No Error - Monkey Patching - NOT RECOMMENDED
# Using Dictionaries
employee_2 = {}
employee_2["name"] = "John"
employee_2["name"] # => John
# employee_2.name # => Error - Cannot access values using .
# Using SimpleNameSpace
# Reference: https://docs.python.org/3/library/types.html#types.SimpleNamespace
from types import SimpleNamespace
employee_3 = SimpleNamespace()
employee_3.name = "John" # => No Error - Not Mokey Patching - Correct Usage
# employee_3["name"] # => Error - Cannot use keys with SimpleNamespace
# Custom SimpleNamespace
from dataclasses import field
from typing import Any
class Employee(SimpleNamespace):
def __setitem__(self, key: str, value: Any) -> None:
setattr(self, key, value)
def __getitem__(self, key: str) -> Any:
return getattr(self, key)
employee_4 = Employee()
employee_4["name"] = "John" # => No Error - Not Mokey Patching - Correct Usage
employee_4.age = 24 # => No Error - Not Mokey Patching - Correct Usage
assert employee_4.name == "John"
assert employee_4["name"] == "John"
assert employee_4.age == 24
assert employee_4["age"] == 24
####################################################
## 7.2 Generators
####################################################
# Reference: https://docs.python.org/3/tutorial/classes.html#generators
from typing import Generator, Iterator, List
def fibonacci_generator() -> Generator[int, None, None]:
last: int = 1
current: int = 1
yield last
yield current
while True:
current, last = last + current, current
yield current
generator = fibonacci_generator()
fibonacci_10_first: List[int] = []
for _ in range(10):
next_fibonacci = next(generator)
fibonacci_10_first.append(next_fibonacci)
assert fibonacci_10_first == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# Can take parameters like any function
def primes_smaller_than(number: int) -> Generator[int, None, None]:
visited: List[int] = []
for number in range(2, number):
not_prime = any(number % possible_divisor == 0 for possible_divisor in visited)
if not_prime:
continue
visited.append(number)
yield number
# With traditional loop
generator = primes_smaller_than(25)
primes_smaller_than_25: List[int] = []
for prime in generator:
primes_smaller_than_25.append(prime)
assert primes_smaller_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
# With comprehension
generator = primes_smaller_than(25)
primes_smaller_than_25 = [prime for prime in generator]
assert primes_smaller_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
# With list
generator = primes_smaller_than(25)
primes_smaller_than_25 = list(generator)
assert primes_smaller_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
####################################################
## 7.3 Iterators
####################################################
# Reference: https://docs.python.org/3/library/stdtypes.html#iterator-types
from dataclasses import dataclass, field
from typing import List
@dataclass
class PrimesSmallerThan:
number: int
current_number: int = 1
visited: List[int] = field(default_factory=list)
def __iter__(self): # Required for use in For
return self
def __next__(self): # Necessary for function next
while True:
self.current_number += 1
no_is_prime = any(
self.current_number % possible_divisor == 0
for possible_divisor in self.visited
)
if self.current_number >= self.number:
raise StopIteration()
if not no_is_prime or len(self.visited) == 0:
break
self.visited.append(self.current_number)
return self.current_number
# With traditional loop
class_generator: Iterator[int] = PrimesSmallerThan(25)
primes_less_than_25: List[int] = []
for prime in class_generator:
primes_less_than_25.append(prime)
assert primes_less_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
# With comprehension
class_generator: Iterator[int] = PrimesSmallerThan(25)
primes_smaller_than_25 = [prime for prime in class_generator]
assert primes_smaller_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
# With list
class_generator: Iterator[int] = PrimesSmallerThan(25)
primes_smaller_than_25 = list(class_generator)
assert primes_smaller_than_25 == [2, 3, 5, 7, 11, 13, 17, 19, 23]
####################################################
## 7.4 Semi-coroutines (Generators with send)
####################################################
from typing import Generator, Any
def accumulate() -> Generator[float, float, None]:
accumulator = 0
while True:
following = yield accumulator
accumulator += following
semicoroutine: Generator[float, float, None] = accumulate()
next(semicoroutine) # Initialize
semicoroutine.send(10)
semicoroutine.send(-1)
accumulator_result: float = semicoroutine.send(20) # Finish
assert accumulator_result == 29
## Use Case
def processing_deferred() -> Generator[Any, Any, Any]:
data = yield
print(f"Processing data... - {data}") # Replace with complex process
processed_data = str(data)
new_data = yield processed_data
print(f"Processing data... - {new_data}") # Replace with complex process
yield "Done"
semicoroutine_deferred: Generator[Any, Any, Any] = processing_deferred()
next(semicoroutine_deferred) # Initialize
deferred_result: float = semicoroutine_deferred.send(123) # => Processing data... - 123
# Deferred processing
deferred_result = semicoroutine_deferred.send(654) # => Processing data... - 654
assert deferred_result == "Done"
####################################################
## 7.5 Corrutinas (AsyncIO)
####################################################
# Reference: https://docs.python.org/3/library/asyncio-task.html
import asyncio
import time
from typing import Tuple
# Defining corrutines
async def processing_db() -> int: # Async modifier
print("DB: Sending database query")
await asyncio.sleep(1) # Similar behavior to yield
print("DB: Processing query 1")
await asyncio.sleep(3)
print("DB: Saving Results")
return 0
async def responding_api() -> int:
print("API: Requesting data from user")
await asyncio.sleep(1)
print("API: Building Response")
await asyncio.sleep(1)
print("API: Writing Logs")
await asyncio.sleep(1)
print("API: Sending Response")
await asyncio.sleep(1)
print("API: Receiving confirmation")
return 1
# Serial Execution of Corrutines
async def main_serial() -> Tuple[int, int]:
result_db = await processing_db()
result_api = await responding_api()
return (result_db, result_api)
async def main_serial_inverted() -> Tuple[int, int]:
result_api = await responding_api()
result_db = await processing_db()
return (result_api, result_db)
print(f"Started: {time.strftime('%X')}")
results: Tuple[int, int] = asyncio.run(main_serial())
print(f"Completed: {time.strftime('%X')}")
assert results == (0, 1)
# Started: 23:22:24
# DB: Sending database query
# DB: Processing query 1
# DB: Saving Results
# API: Requesting data from user
# API: Building Response
# API: Writing Logs
# API: Sending Response
# API: Receiving confirmation
# Completed: 23:22:32
print(f"Started: {time.strftime('%X')}")
results: Tuple[int, int] = asyncio.run(main_serial_inverted())
print(f"Completed: {time.strftime('%X')}")
assert results == (1, 0)
# Started: 23:23:06
# API: Requesting data from user
# API: Building Response
# API: Writing Logs
# API: Sending Response
# API: Receiving confirmation
# DB: Sending database query
# DB: Processing query 1
# DB: Saving Results
# Completed: 23:23:14
# Concurrent execution of Tasks (Tasks)
async def main_task() -> Tuple[int, int]:
db_task = asyncio.create_task(processing_db())
api_task = asyncio.create_task(responding_api())
return (await db_task, await api_task)
async def main_task_inverted() -> Tuple[int, int]:
api_task = asyncio.create_task(responding_api())
db_task = asyncio.create_task(processing_db())
return (await api_task, await db_task)
print(f"Started: {time.strftime('%X')}")
results = asyncio.run(main_task())
print(f"Completed: {time.strftime('%X')}")
assert results == (0, 1)
# Started: 23:23:55
# DB: Sending database query
# API: Requesting data from user
# DB: Processing query 1
# API: Building Response
# API: Writing Logs
# API: Sending Response
# DB: Saving Results
# API: Receiving confirmation
# Completed: 23:23:59
print(f"Started: {time.strftime('%X')}")
results = asyncio.run(main_task_inverted())
print(f"Completed: {time.strftime('%X')}")
assert results == (1, 0)
# Started: 23:24:30
# API: Requesting data from user
# DB: Sending database query
# API: Building Response
# DB: Processing query 1
# API: Writing Logs
# API: Sending Response
# DB: Saving Results
# API: Receiving confirmation
# Completed: 23:24:34
# Concurrent Execution of Corrutines (Gather)
async def main_gather() -> Tuple[int, int]:
return await asyncio.gather(processing_db(), responding_api())
async def main_gather_inverted() -> Tuple[int, int]:
return await asyncio.gather(responding_api(), processing_db())
print(f"Started: {time.strftime('%X')}")
results = asyncio.run(main_gather())
print(f"Completed: {time.strftime('%X')}")
assert results == [0, 1]
# Started: 23:27:10
# DB: Sending database query
# API: Requesting data from user
# DB: Processing query 1
# API: Building Response
# API: Writing Logs
# API: Sending Response
# DB: Saving Results
# API: Receiving confirmation
# Completed: 23:27:14
print(f"Started: {time.strftime('%X')}")
results = asyncio.run(main_gather_inverted())
print(f"Completed: {time.strftime('%X')}")
assert results == [1, 0]
# Started: 23:27:51
# API: Requesting data from user
# DB: Sending database query
# API: Building Response
# DB: Processing query 1
# API: Writing Logs
# API: Sending Response
# DB: Saving Results
# API: Receiving confirmation
# Completed: 23:27:55
# Executing asynchronously synchronous code
# Asynchronously executing synchronous code
import time
import asyncio
from typing import List
def wait() -> None:
time.sleep(1)
def main_blocking() -> List[None]:
return [wait() for _ in range(10)]
async def main_blocking_async():
loop = asyncio.get_running_loop()
futures = [loop.run_in_executor(None, wait) for _ in range(10)]
return await asyncio.gather(*futures)
print(f"Started: {time.strftime('%X')}")
results_blocking: List[None] = main_blocking()
print(f"Completed: {time.strftime('%X')}")
assert results_blocking == [None] * 10
# Started: 23:30:18
# Completed: 23:30:28
print(f"Started: {time.strftime('%X')}")
results_blocking_async: Tuple[None] = asyncio.run(main_blocking_async())
print(f"Completed: {time.strftime('%X')}")
assert results_blocking_async == [None] * 10
# Started: 23:30:59
# Completed: 23:31:00
####################################################
## 7.6 Decorators
####################################################
####################################################
## 7.6.1 Stateless decorators
####################################################
import time
from typing import Tuple, Any
def measure_time(function: Callable[..., Any]) -> Callable[..., Tuple[Any, float]]:
def helper(*args: Any, **kargs: Any) -> Tuple[Any, float]:
"""Helper function"""
start: float = time.perf_counter()
result = function(*args, **kargs)
end: float = time.perf_counter()
elapsed: float = end - start
return result, elapsed
return helper
def slow_function() -> str:
"""Original function"""
time.sleep(2)
return "Hello world"
# Normal invocation
response: str = slow_function()
assert response == "Hello world"
import math
# Invocation with wrapper without decorator
slow_function_with_time = measure_time(slow_function)
result, run_time = slow_function_with_time()
assert result == "Hello world"
assert math.isclose(run_time, 2, abs_tol=0.1)
assert slow_function.__name__ == "slow_function"
assert slow_function_with_time.__name__ == "helper" # Undesirable
assert slow_function_with_time.__doc__ == "Helper function" # Not Desired
# Using wraps to "inherit" name and docstring
from functools import wraps
def measure_time_alternative(
function: Callable[..., Any]
) -> Callable[..., Tuple[Any, float]]:
@wraps(function)
def helper(*args: Any, **kargs: Any) -> Tuple[Any, float]:
start: float = time.perf_counter()
result = function(*args, **kargs)
end: float = time.perf_counter()
elapsed: float = end - start
return result, elapsed
return helper
slow_function_with_time = measure_time_alternative(slow_function)
result, execution_time = slow_function_with_time()
assert result == "Hello world"
assert math.isclose(execution_time, 2, abs_tol=0.1)
assert slow_function.__name__ == "slow_function"
assert slow_function_with_time.__name__ == "slow_function" # Desirable
assert slow_function_with_time.__doc__ == "Original function" # Desirable
# Invocation with decorator
@measure_time_alternative
def function_slow_measure():
time.sleep(2)
return "Hello world"
result, execution_time = function_slow_measure()
assert result == "Hello world"
assert math.isclose(execution_time, 2, abs_tol=0.1)
# Stateful decorator
def count_runs(function: Callable[..., Any]) -> Callable[..., Any]:
@wraps(function)
def helper(*args: Any, **kwargs: Any):
helper.runs += 1
return function(*args, **kwargs)
helper.runs = 0 # Warning - Monkey Patching - NOT RECOMMENDED
return helper
@count_runs
def function_count() -> str:
return "Hello world"
for _ in range(10):
function_count()
assert function_count.runs == 10 # Warning Unknown attribute
####################################################
## 7.6.2 Stateful Decorators
####################################################
from dataclasses import dataclass
from typing import Callable
@dataclass
class Counter:
func: Callable[..., Any]
runs: int = 0
def __call__(self, *args: Any, **kwargs: Any) -> Any:
self.runs += 1
return self.func(*args, **kwargs)
@Counter
def function_counted_class():
return "Hello world"
for _ in range(10):
function_counted_class()
assert function_counted_class.runs == 10 # No Warning
# Use cases - Cache and Memoization Manual
@Counter
def fibonacci(number: int) -> int:
if number < 2:
return number
return fibonacci(number - 1) + fibonacci(number - 2)
result = fibonacci(20)
assert result == 6765
assert fibonacci.runs == 21_891
from typing import Dict
def memoization(function: Callable[..., Any]) -> Callable[..., Any]:
cache: Dict[str, Any] = {}
def helper(*args: Any, **kwargs: Any) -> Any:
nonlocal cache
key = str(tuple(sorted(args)) + tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = function(*args, **kwargs)
return cache[key]
return helper
@Counter
@memoization
def fibonacci_memo(number: int) -> int:
if number < 2:
return number
return fibonacci_memo(number - 1) + fibonacci_memo(number - 2)
result = fibonacci_memo(20)
assert result == 6765
assert fibonacci_memo.runs == 39 # 500 times fewer runs
# Use cases - Cache and Memoization LRU
from functools import lru_cache
# Reference: https://docs.python.org/3/library/functools.html#functools.lru_cache
@Counter
@lru_cache(maxsize=None) # Equivalent to @cache in Python 3.9+
def fibonacci_lru(number: int) -> int:
if number < 2:
return number
return fibonacci_lru(number - 1) + fibonacci_lru(number - 2)
result = fibonacci_lru(20)
assert result == 6765
assert fibonacci_memo.runs == 39 # 500 times fewer runs
####################################################
## 7.7 Context Manager
####################################################
# Reference: https://docs.python.org/3/library/stdtypes.html#context-manager-types
####################################################
## 7.7.1 Context Manager with Classes
####################################################
from dataclasses import dataclass
from typing import IO, Optional, Any
import time
@dataclass
class Timer:
start: float = 0
end: Optional[float] = None
elapsed: float = -1
exception: bool = False
def __enter__(self) -> Timer:
self.start = time.perf_counter()
return self
def __exit__(self, exception_type: Optional[Any], _: Any, __: Any) -> bool:
self.exception = exception_type is not None
self.end = time.perf_counter()
self.elapsed = round(self.end - self.start, 3)
return True
with Timer() as tempo:
time.sleep(5)
raise ValueError
print(tempo) # => Timer(start=0.1141484, end=5.1158644, elapsed=5.002, exception=True)
assert math.isclose(tempo.elapsed, 5, abs_tol=0.1)
assert tempo.exception == True
####################################################
## 7.7.2 Context Manager with Generators and Contextlib
####################################################
## Reference: https://docs.python.org/3/library/contextlib.html
from contextlib import contextmanager
import time
@contextmanager
def timer():
internal_data = {
"start": time.perf_counter(),
"end": -1,