Advanced topics in Python programming#

This notebook explores (slightly) more advanced elements of programming in Python. Among other things we will look into

  • functional programming

  • generators/iterators

  • documenting code

  • error handling

One aspect not addressed here is writting code following the PEP8 style guide, e.g. indentations, class/function names. There are tools to format your code that way (often given as extension to IDEs), for example flake8.

Bits of functional programming#

We have seen how to define a function, i.e. give it a name

def identity(x): return x

However, sometimes we might have use for nameless function - enter Anonymous functions. For example in sorting

import random

# Let's generate random pairs with the idea of sorting them later
random_tuples = []
for i in range(10):
    random_tuples.append((random.random(), random.random()))
random_tuples
[(0.9511176424926535, 0.9742813887530748),
 (0.5776776069602639, 0.10447364475487353),
 (0.37608222708654293, 0.6486109614387363),
 (0.30945796282871496, 0.07954468498467404),
 (0.4996430964021168, 0.32581504743166245),
 (0.24952665159729226, 0.7523088865961022),
 (0.7093848623063937, 0.016854321726398114),
 (0.9572218713564041, 0.3209356903789915),
 (0.1092176594392319, 0.020611646926582128),
 (0.9071444097710661, 0.8585649655113832)]
# By default tuples are sorted by considering first the first elements, then comparing the rest, i.e.
sorted(random_tuples)
[(0.1092176594392319, 0.020611646926582128),
 (0.24952665159729226, 0.7523088865961022),
 (0.30945796282871496, 0.07954468498467404),
 (0.37608222708654293, 0.6486109614387363),
 (0.4996430964021168, 0.32581504743166245),
 (0.5776776069602639, 0.10447364475487353),
 (0.7093848623063937, 0.016854321726398114),
 (0.9071444097710661, 0.8585649655113832),
 (0.9511176424926535, 0.9742813887530748),
 (0.9572218713564041, 0.3209356903789915)]
# Treating them as points we might want to consider their l^2 norm
sorted(random_tuples, key=lambda t: (t[0] ** 2 + t[1] ** 2) ** 0.5)
[(0.1092176594392319, 0.020611646926582128),
 (0.30945796282871496, 0.07954468498467404),
 (0.5776776069602639, 0.10447364475487353),
 (0.4996430964021168, 0.32581504743166245),
 (0.7093848623063937, 0.016854321726398114),
 (0.37608222708654293, 0.6486109614387363),
 (0.24952665159729226, 0.7523088865961022),
 (0.9572218713564041, 0.3209356903789915),
 (0.9071444097710661, 0.8585649655113832),
 (0.9511176424926535, 0.9742813887530748)]
min(random_tuples, key=lambda t: (t[0] ** 2 + t[1] ** 2) ** 0.5)
(0.1092176594392319, 0.020611646926582128)

Here lambda is a key word used for defining anonymous functions. It is followed by arguments. Above the function accepts one argument (referred to as t). The function body follows after :. Side note, \(\lambda\)-calculus and its inventor Alonzo Church

In capturing variables beware of late binding

# The idea is that foos[1](x) should return x+1
foos = [lambda x: x + n for n in range(5)]
# But ...
for f in foos:
    print(f(0))
4
4
4
4
4

Definition is evaluated at runtime (then n = 4) and not at definition time

# Solution [referred to as currying]
foos = [lambda x, n=n: x + n for n in range(5)]
for f in foos:
    print(f(0))
0
1
2
3
4

Anonymous functions are often used to build generator. Here the idea is that we want to compute on demand and not all the answers at once.

selected = filter(lambda p: p[0] < 0.5, random_tuples)
# Not the answers but ...
selected
<filter at 0x105bd28f0>
# Generator are iterated over
next(selected)
(0.37608222708654293, 0.6486109614387363)
# or consumed entirely
for item in selected:
    print(item)
(0.30945796282871496, 0.07954468498467404)
(0.4996430964021168, 0.32581504743166245)
(0.24952665159729226, 0.7523088865961022)
(0.1092176594392319, 0.020611646926582128)
# Note that we have now exhausted the iterator so that the following attempt to get the next item fails
next(selected)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
Cell In[10], line 2
      1 # Note that we have now exhausted the iterator so that the following attempt to get the next item fails
----> 2 next(selected)

StopIteration: 

Iterators can be combined to build processing pipelines

# Keep only the elements in iterable for which the function is true
selected = filter(lambda p: p[0] < 0.5, random_tuples)
# Apply sum function to all the elements in iterable
processed = map(sum, selected)
processed
<map at 0x106cc46a0>

What is the sum of such elements ? One option is

sum(list(processed))

Also sum(processed) would work but we want to showcase a nice module from the standard library, namely, functools.

# Option 1) to comsume and turn into a list
from functools import reduce

# combine first two items of iterable to make the input
# for next round while the other argument is the next item in iterable
reduce(lambda x, y: x + y, processed)
3.370818824731656

Food for thought:

  1. Could we use reduce(sum, processed) above ?

  2. What does functools.partial do?

  3. Which digits are common to all entries obtained by summing tuples in random_tuples?

import operator


def digits(num):
    """Set of digits of the number"""
    return set(filter(str.isdecimal, str(num)))


# To find the answer we reduce by set intersection
reduce(operator.and_, (map(lambda t: digits(t[0] + t[1]), random_tuples)))
{'1', '3', '8'}

Many useful iterators can be constructed using standard library module itertools. Let’s do cartesian coordinates

from itertools import product

x = range(1, 5)
y = range(4, 12)
grid = product(x, y)
# Get them all
print(list(grid))
[(1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11)]

Using itertools.permutations, itertools.combinations we can save ourselves writing a lot to nested for loop. For example: Which number 1 <= a < b < c <= 100 for Pythagorean trippets?

tripplets = []
for a in range(1, 101):
    for b in range(a, 101):
        for c in range(b, 101):
            # Short circuit
            # arg0 and arg1 evals arg1 only if arg0 is True because
            # arg0 False determined the boolean value of the expression
            # Alternative to if
            a**2 + b**2 == c**2 and tripplets.append((a, b, c))

Contrast with

from itertools import combinations

tripplets2 = []
for a, b, c in combinations(range(1, 101), 3):
    a**2 + b**2 == c**2 and tripplets2.append((a, b, c))
# Or even shorter with list comprehensions, see later
set(tripplets) == set(tripplets2)
True

Another example of ondemand/lazy computations are generators. They are introduced by yield keyword.

def even_numbers():
    k = 1
    while True:
        yield 2 * k
        k += 1
evens = even_numbers()

We can start consuming the generator. For example take the first items

# NOTE: zip - pairs iterables into tuples, terminating when one of them is exhaused [range(5) determines this above]
# We can run this many times.
for v, _ in zip(evens, range(5)):  # And some more ...
    print(v)
2
4
6
8
10

Here we use itertools’s count which is counts from argument upwards

from itertools import count  # range()


def odd_numbers():
    for v in count(1):
        yield 2 * v - 1
for v, _ in zip(odd_numbers(), range(5)):
    print(v)
1
3
5
7
9

In the previous example we were consuming other iterator which was built in count. Would the definition of count below accomplish the same?

def count(n):
    yield n
    yield from count(n + 1)


numbers = count(-10)
for i in range(10_000):  # How about counting longer (1_000) ?
    print(next(numbers))
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
0
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
Cell In[22], line 8
      6 numbers = count(-10)
      7 for i in range(10_000):  # How about counting longer (1_000) ?
----> 8     print(next(numbers))

Cell In[22], line 3, in count(n)
      1 def count(n):
      2     yield n
----> 3     yield from count(n + 1)

Cell In[22], line 3, in count(n)
      1 def count(n):
      2     yield n
----> 3     yield from count(n + 1)

    [... skipping similar frames: count at line 3 (2971 times)]

Cell In[22], line 3, in count(n)
      1 def count(n):
      2     yield n
----> 3     yield from count(n + 1)

RecursionError: maximum recursion depth exceeded

The issue with our definition is that it is recursive and the calls go to stack

import sys

sys.getrecursionlimit()
# sys.setrecursionlimit(3_000)
3000

However, increasing the stack size doesn’t always cut it. The recursive implementation often yields to exponentially growing execution time (and memory). The notorious example of this is (doubly recursive) Fibonacci numbers.

from itertools import count


def fib(k):
    assert k > 0
    if k == 1:
        return 1
    if k == 2:
        return 1
    return fib(k - 1) + fib(k - 2)


def fibs():
    """Generator for all of them"""
    for k in count(1):
        yield fib(k)

Let’s look at peformance

from itertools import islice  # Iterator slice
from time import perf_counter

t0 = perf_counter()
for i, k in enumerate(islice(fibs(), 40)):
    t1 = perf_counter()
    print(f"{i} -> {k} in {(t1 - t0):.5f}s")
    t0 = t1
0 -> 1 in 0.00006s
1 -> 1 in 0.00003s
2 -> 2 in 0.00001s
3 -> 3 in 0.00001s
4 -> 5 in 0.00000s
5 -> 8 in 0.00000s
6 -> 13 in 0.00000s
7 -> 21 in 0.00001s
8 -> 34 in 0.00001s
9 -> 55 in 0.00001s
10 -> 89 in 0.00002s
11 -> 144 in 0.00002s
12 -> 233 in 0.00004s
13 -> 377 in 0.00006s
14 -> 610 in 0.00010s
15 -> 987 in 0.00016s
16 -> 1597 in 0.00025s
17 -> 2584 in 0.00041s
18 -> 4181 in 0.00065s
19 -> 6765 in 0.00100s
20 -> 10946 in 0.00151s
21 -> 17711 in 0.00237s
22 -> 28657 in 0.00325s
23 -> 46368 in 0.00535s
24 -> 75025 in 0.00856s
25 -> 121393 in 0.01399s
26 -> 196418 in 0.02200s
27 -> 317811 in 0.03579s
28 -> 514229 in 0.05784s
29 -> 832040 in 0.09766s
30 -> 1346269 in 0.15621s
31 -> 2178309 in 0.24385s
32 -> 3524578 in 0.40004s
33 -> 5702887 in 0.64227s
34 -> 9227465 in 1.03693s
35 -> 14930352 in 1.67304s
36 -> 24157817 in 2.70860s
37 -> 39088169 in 4.40471s
38 -> 63245986 in 7.18042s
39 -> 102334155 in 11.64312s

After a while the time till next number behaves like the Fibonacci sequence itself! We are better off with iterations:

def fibs():
    """Generate Fibonacci numbers"""
    a, b = 0, 1
    while True:
        a, b = a + b, a
        yield a  # Yield keyword makes this function a generator


numbers = fibs()
# Let get first ten
for i, num in zip(range(50), numbers):
    print(i, num)
0 1
1 1
2 2
3 3
4 5
5 8
6 13
7 21
8 34
9 55
10 89
11 144
12 233
13 377
14 610
15 987
16 1597
17 2584
18 4181
19 6765
20 10946
21 17711
22 28657
23 46368
24 75025
25 121393
26 196418
27 317811
28 514229
29 832040
30 1346269
31 2178309
32 3524578
33 5702887
34 9227465
35 14930352
36 24157817
37 39088169
38 63245986
39 102334155
40 165580141
41 267914296
42 433494437
43 701408733
44 1134903170
45 1836311903
46 2971215073
47 4807526976
48 7778742049
49 12586269025

When we care about all results of pipeline it might be better/more explicit/readbable to use comprehensions. Here we consider list and dictionary comprehensions.

with open("./data/file.txt") as stream:
    # NOTE: with invokes a context manager. We want to manage resources;
    # here open a file and then make sure that it is correctly closed no matter what
    # will happen during manipulation, e.g. some error
    lines = [float(line.strip()) for i, line in enumerate(stream) if i % 2]

    # A Dictionary comprehension, create dict mapping row number to value
    d = {i: float(line.strip()) for i, line in enumerate(stream) if i % 2}


# To be compared with
with open("./data/file.txt") as stream:
    iterator = map(
        lambda p: float(p[1].strip()), filter(lambda p: p[0] % 2, enumerate(stream))
    )
    lines_ = list(iterator)
# Check that they are the same. We will come back to the `assert` statement shortly
assert lines == lines_
(d, bool(lines))
({}, True)

Food for thought:

  1. Why is the dictionary empty while we clearly have lines as a non-empty list?

  2. What is the performance of building list by for-loop versus list comprehensions? [Consider %%timeit magic]

%%timeit


def f(string):
    return sum(map(ord, string))


f("IN3110")
276 ns ± 1.33 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

While there are set comprehensions, one has to be careful with “tuple” comprehensions

{l for l in "aqowngeåonewvewuw"}
{'a', 'e', 'g', 'n', 'o', 'q', 'u', 'v', 'w', 'å'}
(v for v in islice(fibs(), 20) if v % 2)
<generator object <genexpr> at 0x105bb6190>
tuple(v for v in islice(fibs(), 20) if v % 2)
(1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597, 4181, 6765)

The with keyword is an entry point for contextmanager Its functionality is useful when there is some setup and tear-down needed before and after computations. Typical example is writing to file.

# Only write in caps


class CapsFile:
    # __enter__ and __exit__ special for context manager protocol
    def __init__(self, file_name, mode):
        self.file_obj = open(file_name, mode)
        write = self.file_obj.write
        # Here we replace the file object's write method
        self.file_obj.write = lambda w, write=write: write(w.upper())

    def __enter__(self):
        return self.file_obj

    def __exit__(self, type, value, traceback):
        self.file_obj.close()


with CapsFile("tes.t", "w") as out:
    out.write("Hello weltx")
    # raise ValueError

See about the result

cat tes.t
HELLO WELTX

Writing cleaner functions#

(Personal opinion) A good function 1) does what it is supposed to do, 2) does it quickly, 3) is user/developer friendly. Here we will focus on friendlines

Python uses so called duck-typing but we can express our intensions of the input arguments and function output by type annotations. These can be checked by mypy (but are not enforced)

# Following is code included in factorial.py.
def factorial(n: int) -> int:
    if n == 0:
        return 1
    return n*factorial(n-1)

factorial('works?')

We run type analysis by

(in3110) mirok@evalApply:data|$ mypy factorial.py 

Role of arguments should be clarified in a docstring of a function (or class). Type can be part of the docstring. We can also include tests via doctest. Documentation in the form of for example HTML pages can be generated by shinx. The following illustates a doctring with some nonexhaustive tests. For examples of Google-style docstrings see here

# Part of factorial_doctest.py
def factorial(n: int) -> int:
    '''Return the factorial of n, an exact integer >= 0.

    Args:
       n (int):  n!

    Returns:
       int.  The factorial value::

    >>> factorial(5)
    120
    >>> factorial(0)
    1

    '''
    if n == 0:
        return 1
    return n*factorial(n-1)

To run the doctest we execute

(in3110) mirok@evalApply:data|$ python factorial_doctest.py -v

We will come back to testing when discussing Python package development in the next part.

Enforcing the behaviour via exceptions (and their handling). There are several predifined exception types: eg. ValueError, AssertionError, MethodError. We can also define our own type.

class MyError(BaseException):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return f'MyError occured with error message "{self.msg}"'
# This is contrived to illustrate the custom exceptions in action.


def factorial(n: int) -> int:
    """Return the factorial of n, an exact integer >= 0.

    Args:
       n (int):  n!

    Returns:
       int.  The factorial value::

    >>> factorial(5)
    120
    >>> factorial(0)
    1
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: Only non-negative inputs are expected
    """
    # Raise AssertionError if the type is wrong
    assert isinstance(n, int)
    # Raise a different exception for negative integers
    if n < 0:
        raise ValueError("Only non-negative inputs are expected")

    if n == 42:
        raise MyError("This is not meant to be")

    if n == 0:
        return 1
    return n * factorial(n - 1)

Handling the raised exceptions. There are several predifined expection types: eg. ValueError, AssertionError, MethodError. We can also define our own type.

val = -4  #  32

try:
    f = factorial(val)
# We will try with the integer value
except AssertionError:
    from math import ceil

    n = ceil(val)
    print(f"Calling instead with {n}")
    f = factorial(n)

# Let's say that for negative we flip the sign
except ValueError:
    n = -val
    print(f"Calling instead with {n}")
    f = factorial(n)

except MyError as e:
    print("42!")

finally:
    # Sieve through here
    pass
Calling instead with 4

Modifying function behavior#

By now we have written function, we have seen functions that take in functions. What we want to do now is to write functions that return modified functions. In our first example we want to write a function which modifies the input function with timing information.

import time
from functools import wraps


def timeit(foo):
    """Return exacution time"""

    @wraps(foo)
    def wrapper(*args, **kwargs):
        then = time.perf_counter()
        result = foo(*args, **kwargs)
        now = time.perf_counter()
        print(f"{foo.__name__} executed in {now-then} s")

        return result

    return wrapper

Here we use the @wraps in order to preserve metadata of foo (see below). Let’s write the function to be timed.

def one_second():
    time.sleep(1)


print(one_second())

timed = timeit(one_second)
# As a **Food for thought** omit the @wraps decorator above and consider what happens with timed.__name__
timed.__name__
None
'one_second'
print(timed())
one_second executed in 1.0050931249988935 s
None

A syntactic sugar for applying timeit is via @

@timeit
def one_second():
    time.sleep(1)


print(one_second())
one_second executed in 1.0040542499991716 s
None

As another example of decorators consider memoization is a technique for caching the function’s return value for given input such that it does not need to be computed again. We can test the idea with the functools.lru_cache decorator.

from functools import lru_cache


def slow_factorial(n):
    """Factorial by recursion"""
    if n == 0:
        return 1
    return n * slow_factorial(n - 1)


@lru_cache
def faster_factorial(n):
    return slow_factorial(n)

Let’s see about the speed

%timeit slow_factorial(10)
567 ns ± 6.84 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
%timeit faster_factorial(10)
37.9 ns ± 0.171 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

As an exercise let’s write the cache decorator ourselves. However, unlike in @timeit we want to make a decorator which takes in an argument which is the cache size. Note that @lru_cache has this behavior too. We base our cache on a dictionary

class Cache(dict):
    def __init__(self, size):
        self.size = size

    def __setitem__(self, key, value):
        # Make room
        if len(self) >= self.size:
            # Grab some key
            key = next(iter(self))
            # and remove the entry
            self.pop(key)
        # Set it via parent (dict class)
        super().__setitem__(key, value)

Recall that decorator with arguments is applied as decorator(arguments)(function). That is decorator(arguments) must return a function

from functools import wraps


def cache(size):
    """Memoize"""

    def decorate(foo):
        memory = Cache(size)

        @wraps(foo)
        def wrapper(*args):
            # Lookup arguments. NOTE: here we only assumed positional arguments
            if args in memory:
                return memory[args]
            # Compute and remember
            result = foo(*args)
            memory[args] = result
            return result

        return wrapper

    return decorate


@cache(10)
def faster_factorial2(n):
    return slow_factorial(n)
faster_factorial2(3)
6

Let’s now speed up Fibinacci with cache

# Speed up Fibinachi with cache


@cache(10_000)
def fib(k):
    assert k > 0
    if k == 1:
        return 1
    if k == 2:
        return 1
    return fib(k - 1) + fib(k - 2)


def fibs():
    """Generator for all of them"""
    for k in count(1):
        yield fib(k)
from time import perf_counter

t0 = perf_counter()
for i, k in enumerate(islice(fibs(), 100)):
    t1 = perf_counter()
    print(f"{i} -> {k} in {(t1 - t0):.5f}s")
    t0 = t1
0 -> 1 in 0.00023s
1 -> 1 in 0.00035s
2 -> 2 in 0.00003s
3 -> 3 in 0.00002s
4 -> 5 in 0.00002s
5 -> 8 in 0.00002s
6 -> 13 in 0.00002s
7 -> 21 in 0.00002s
8 -> 34 in 0.00007s
9 -> 55 in 0.00002s
10 -> 89 in 0.00002s
11 -> 144 in 0.00002s
12 -> 233 in 0.00002s
13 -> 377 in 0.00001s
14 -> 610 in 0.00001s
15 -> 987 in 0.00001s
16 -> 1597 in 0.00001s
17 -> 2584 in 0.00003s
18 -> 4181 in 0.00002s
19 -> 6765 in 0.00001s
20 -> 10946 in 0.00001s
21 -> 17711 in 0.00002s
22 -> 28657 in 0.00001s
23 -> 46368 in 0.00001s
24 -> 75025 in 0.00001s
25 -> 121393 in 0.00001s
26 -> 196418 in 0.00001s
27 -> 317811 in 0.00002s
28 -> 514229 in 0.00001s
29 -> 832040 in 0.00001s
30 -> 1346269 in 0.00001s
31 -> 2178309 in 0.00001s
32 -> 3524578 in 0.00001s
33 -> 5702887 in 0.00002s
34 -> 9227465 in 0.00001s
35 -> 14930352 in 0.00001s
36 -> 24157817 in 0.00001s
37 -> 39088169 in 0.00001s
38 -> 63245986 in 0.00001s
39 -> 102334155 in 0.00002s
40 -> 165580141 in 0.00001s
41 -> 267914296 in 0.00001s
42 -> 433494437 in 0.00002s
43 -> 701408733 in 0.00001s
44 -> 1134903170 in 0.00001s
45 -> 1836311903 in 0.00001s
46 -> 2971215073 in 0.00001s
47 -> 4807526976 in 0.00002s
48 -> 7778742049 in 0.00001s
49 -> 12586269025 in 0.00001s
50 -> 20365011074 in 0.00001s
51 -> 32951280099 in 0.00001s
52 -> 53316291173 in 0.00001s
53 -> 86267571272 in 0.00001s
54 -> 139583862445 in 0.00001s
55 -> 225851433717 in 0.00002s
56 -> 365435296162 in 0.00001s
57 -> 591286729879 in 0.00001s
58 -> 956722026041 in 0.00001s
59 -> 1548008755920 in 0.00003s
60 -> 2504730781961 in 0.00001s
61 -> 4052739537881 in 0.00001s
62 -> 6557470319842 in 0.00001s
63 -> 10610209857723 in 0.00001s
64 -> 17167680177565 in 0.00001s
65 -> 27777890035288 in 0.00001s
66 -> 44945570212853 in 0.00001s
67 -> 72723460248141 in 0.00002s
68 -> 117669030460994 in 0.00001s
69 -> 190392490709135 in 0.00001s
70 -> 308061521170129 in 0.00001s
71 -> 498454011879264 in 0.00001s
72 -> 806515533049393 in 0.00001s
73 -> 1304969544928657 in 0.00001s
74 -> 2111485077978050 in 0.00001s
75 -> 3416454622906707 in 0.00001s
76 -> 5527939700884757 in 0.00001s
77 -> 8944394323791464 in 0.00001s
78 -> 14472334024676221 in 0.00001s
79 -> 23416728348467685 in 0.00001s
80 -> 37889062373143906 in 0.00001s
81 -> 61305790721611591 in 0.00002s
82 -> 99194853094755497 in 0.00002s
83 -> 160500643816367088 in 0.00001s
84 -> 259695496911122585 in 0.00001s
85 -> 420196140727489673 in 0.00002s
86 -> 679891637638612258 in 0.00001s
87 -> 1100087778366101931 in 0.00001s
88 -> 1779979416004714189 in 0.00001s
89 -> 2880067194370816120 in 0.00001s
90 -> 4660046610375530309 in 0.00001s
91 -> 7540113804746346429 in 0.00001s
92 -> 12200160415121876738 in 0.00001s
93 -> 19740274219868223167 in 0.00001s
94 -> 31940434634990099905 in 0.00001s
95 -> 51680708854858323072 in 0.00001s
96 -> 83621143489848422977 in 0.00001s
97 -> 135301852344706746049 in 0.00001s
98 -> 218922995834555169026 in 0.00001s
99 -> 354224848179261915075 in 0.00001s

Some other useful decorators are @property in class definitions.

class UnixName:
    """Max 8 characters"""

    def __init__(self, name):
        self.name = name  # NOTE: here were're calling the setter

    # Get
    @property
    def name(self):
        return self._name

    # Set
    @name.setter
    def name(self, name):
        if len(name) > 8:
            name = name[:8]
        self._name = name


(UnixName("Miro").name, UnixName("MiroslavKuchta").name)
('Miro', 'Miroslav')

Some extras for class: we have seen special methods that hook up e.g. to arithmetic ‘+’ (__add__) or interact with with (__enter__). What if you want to make your class iterable? In the example below we would like to iterate over a word in a special way where each letter is (shifter)[https://en.wikipedia.org/wiki/Caesar_cipher]

# __iter__ method


class Ceasar:
    def __init__(self, word, shift=2):
        assert word.isalpha()
        assert word.lower() == word
        self.word = word
        self.shift = shift

    def __iter__(self):
        for ch in self.word:
            yield chr(ord(ch) + self.shift)
for l, c in zip("helloworld", Ceasar("helloworld")):
    print(f"{l} -> {c}")
h -> j
e -> g
l -> n
l -> n
o -> q
w -> y
o -> q
r -> t
l -> n
d -> f

Note that many things can be iterated over - list produces its items, str the individual characters. Then it makes sense to ask for the first element. We know we list and str we are good

a = [2, 3, 4]
assert a[0] == 2

How would we get first element of a say a set?

things = set(map(chr, range(35, 40)))
things[1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[53], line 2
      1 things = set(map(chr, range(35, 40)))
----> 2 things[1]

TypeError: 'set' object is not subscriptable
# See Peter Norvig's https://github.com/norvig/pytudes


def first(iterable):
    # By iter we make sure we have something for which `next` can be called
    return next(iter(iterable))


first(things)
"'"

See more at Peter Norvig’s pytudes

Some review projects#

The let block#

In Julia language the let keyword introduces a new scope, i.e. we can e.g. have local variables named as global ones without interference. We would like to do something similar in python. Of course one option is a function - function body is a new scope.

import importlib

a = 2


def let(np=importlib.import_module("numpy")):
    a = 4
    return np.zeros((a, a))


print(let(), a)
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]] 2

But this let is quite cumbersome. We can do [better](# Inspired by https://stackoverflow.com/questions/61371134/python-let-with-local-scopes-debug-printing-and-temporary-variables )

from contextlib import contextmanager
from inspect import currentframe, getouterframes

@contextmanager
def let(**bindings):
    # 2 because first frame in `contextmanager` is the decorator      
    frame = getouterframes(currentframe(), 2)[-1][0] 
    locals_ = frame.f_locals
    original = {var: locals_.get(var) for var in bindings}
    locals_.update(bindings)
    yield
    locals_.update(original)
    # Cleanup with keeping in scope the vars that were there originally
    for var in set(bindings).difference(locals_):
        del locals_[var]

We can now do something like this

import importlib
    
b = 3
with let(np=importlib.import_module('numpy'), x=2, y=4, b=5):
    ans = np.zeros((x, y))

print(ans)
print('b is as before let', b)
try:
    print(np, x, y)
except NameError:
    print('np x y not visible in this scope')

Fun with annotations#

Putting some of the lessons learned today and last time together: the following is heavily inspired by talk by David Beazley, see (YouTube)[https://www.youtube.com/watch?v=js_0wjzuMfc&t=3s] for original. We have seen that type annotations can be used for static type checking. Here we would like to “hook” into the type system with (i) our own types and (ii) at runtime. Think for example a function set_month that should take only non-empty strings containing [A-Z][a-z]

def set_month(x : AlphaString):
    return x

We begin by getting out custom string type by (multiple) inheritance

class Contract:
    @classmethod
    def check(cls, val):
        pass


class Typed(Contract):
    type = None

    @classmethod
    def check(cls, val):
        assert isinstance(val, cls.type)
        super().check(val)


class String(Typed):
    type = str


class NonEmpty(Contract):
    @classmethod
    def check(cls, val):
        assert len(val) > 0
        super().check(val)


class AlphaString(String, NonEmpty):
    @classmethod
    def check(cls, val):
        assert val.isalpha()
        super().check(val)


AlphaString.check("mkds6")
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[56], line 34
     30         assert val.isalpha()
     31         super().check(val)
---> 34 AlphaString.check("mkds6")

Cell In[56], line 30, in AlphaString.check(cls, val)
     28 @classmethod
     29 def check(cls, val):
---> 30     assert val.isalpha()
     31     super().check(val)

AssertionError: 

Now we would like to declare the argument type and enforce it. Of course we could put all in type assertions in the function’s body but we have in mind using this pattern a lot and don’t want to have these hand-written checks at the beginning of our code

def set_month(x : AlphaString):
    return x

For modifying function behaviour we have before used decorators …

import inspect
from functools import wraps


def checked(func):
    signature = inspect.signature(func)
    annotations = func.__annotations__

    @wraps(func)
    def wrapper(*args, **kwargs):
        # Bind arguments(names) to their values
        bound = signature.bind(*args, **kwargs)
        for varname, value in bound.arguments.items():
            if varname in annotations:
                # For each annotated argument check the bound value
                typed = annotations[varname]
                typed.check(value)
        # If everything is okay we can call func
        return func(*args, **kwargs)

    return wrapper
@checked
def set_month(x: AlphaString):
    return x


set_month("janua7ry")
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[58], line 6
      1 @checked
      2 def set_month(x: AlphaString):
      3     return x
----> 6 set_month("janua7ry")

Cell In[57], line 17, in checked.<locals>.wrapper(*args, **kwargs)
     14     if varname in annotations:
     15         # For each annotated argument check the bound value
     16         typed = annotations[varname]
---> 17         typed.check(value)
     18 # If everything is okay we can call func
     19 return func(*args, **kwargs)

Cell In[56], line 30, in AlphaString.check(cls, val)
     28 @classmethod
     29 def check(cls, val):
---> 30     assert val.isalpha()
     31     super().check(val)

AssertionError: 

More fun with annotations#

In C++ we can have functions with the same name but differing by arguments (types or count) and the right function to be called will be determined by the arguments at compile time. In python, this idea can be accomplished e.g. by

def foo(a, b=None):
    if b is None:
        b = 2
    if isinstance(b, float):
        return a*b
    return a+b
def foo(a, b=None):
    if b is None:
        b = 2
    if isinstance(b, float):
        return a * b
    return a + b


(foo(2, 3), foo(2, 3.0), foo(2))
(5, 6.0, 4)

While this works the if statements make the code somewhat convoluted. Since we have the type annotations, wouldn’t it be nicer if something like this was possible?

def foo(a: int, b: int):
    return a + b

def foo(a: int, b: float):
    return a*b

def foo(a: int):
    return foo(2, a)

We take some inspiration from Python’s founder Guido van Rossum’s recipe

class MultiMethod:
    def __init__(self, name):
        self.name = name
        self.typemap = {}

    def __call__(self, *args):
        """Dispatch to method based on type of the arguments"""
        types = tuple(arg.__class__ for arg in args)
        function = self.typemap.get(types, None)
        if function is None:
            raise TypeError("no match")
        return function(*args)

    def register(self, types, function):
        """Add"""
        if types in self.typemap:
            raise TypeError("duplicate registration")
        self.typemap[types] = function
import inspect

_FUNC_TABLE_ = {}


def multimethod(func):
    signature = inspect.signature(func)
    annotations = func.__annotations__
    # Pull out type annotations to define the type signature
    type_info = tuple(annotations[arg] for arg in signature.parameters)

    name = func.__name__
    mm = _FUNC_TABLE_.get(name)
    if mm is None:
        mm = _FUNC_TABLE_[name] = MultiMethod(name)
    # Register the implementation for that name and the signature
    mm.register(type_info, func)
    return mm
# In action


@multimethod
def bar(a: int, b: int):
    return a + b


@multimethod
def bar(a: int, b: float):
    return a * b


@multimethod
def bar(a: int):
    return bar(2, a)
(bar(2, 3), bar(2, 3.0), bar(2))
(5, 6.0, 4)

Back to \(\lambda\)-calculus#

In (Scheme)(https://en.wikipedia.org/wiki/Scheme_(programming_language)) and other Lisp there is are functions cons, car and cdr that (for the purpose of this project) behave such that

car(cons(a, b)) == a
cdr(cond(a, b)) == b

If we were to implement the 3 functions based only on this specification we could reach out to list or tuples, i.e. rely on some data structure

cons = lambda a, b: (a, b)

car = lambda p: p[0]
cdr = lambda p: p[1]
a, b = 2, 3

car(cons(a, b)) == a
cdr(cons(a, b)) == b
True

In this spirit of \(\lambda\) calculus we can as whether we need data structures? Afterall, everyhing should be possible with just functions

def cons(a, b):
    return lambda f: f(a, b)


def car(thing):
    return thing(lambda p, q: p)


def cdr(thing):
    return thing(lambda p, q: q)
a, b = 2, 3

car(cons(a, b)) == a
cdr(cons(a, b)) == b
True

See Structured and Interpretetion of Computer Programs for more inspiration.