forked from gto76/python-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2299 lines (1942 loc) · 188 KB
/
index.html
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
<!DOCTYPE html>
<html class="ocks-org do-not-copy">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<title>Comprehensive Python Cheatsheet</title>
<meta name="description" content="Exhaustive, simple, beautiful and concise. A truly pythonic cheat sheet about Python programming language.">
<link rel="icon" href="web/favicon.png">
<link rel="stylesheet" href="web/default.min.css">
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Comprehensive Python Cheatsheet">
<meta name="twitter:description" content="Exhaustive, simple, beautiful and concise. A truly pythonic cheat sheet about Python programming language.">
<meta name="twitter:image" content="https://gto76.github.io/python-cheatsheet/web/image_twitter_card_2.jpeg">
<meta name="google-site-verification" content="w3rvuG0D1kUm_w20qsJecSEZh59Am8jK4eSPVU83e_M" />
</head>
<style>
@import url(web/style.css);
.join,
.link,
.node rect {
fill: none;
stroke: #636363;
stroke-width: 1.5px;
}
.link {
stroke: #969696;
}
.node rect {
fill: white;
}
.link path,
.node rect,
.node text,
.join {
-webkit-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
-moz-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
-ms-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
-o-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
}
.node .element rect {
fill: #bdbdbd;
stroke: none;
}
.node .null rect {
fill: none;
stroke: none;
}
.node .null text {
fill: #636363;
}
.node .selection rect {
stroke: #e6550d;
}
.node .data rect {
stroke: #3182bd;
}
.node .datum rect {
fill: #d9d9d9;
stroke: none;
}
.node .code text {
font-family: monospace;
}
.node .key rect {
fill: #a1d99b;
stroke: none;
}
.link .to-key,
.join {
stroke: #a1d99b;
}
.join {
stroke-dasharray: 2,2;
}
.link .to-null {
stroke-dasharray: .5,3.5;
stroke-linecap: round;
}
.link .from-data {
stroke: #3182bd;
}
.play circle {
fill: #fff;
stroke: #000;
stroke-width: 3px;
}
.play:hover path {
fill: #f00;
}
.play.mousedown circle {
fill: #f00;
}
.play.mousedown path {
fill: #fff;
}
.play rect {
fill: none;
pointer-events: all;
cursor: pointer;
}
code span {
-webkit-transition: background 250ms linear;
-moz-transition: background 250ms linear;
-ms-transition: background 250ms linear;
-o-transition: background 250ms linear;
transition: background 250ms linear;
}
pre.prettyprint, code.prettyprint {
background-color: #222;
border-radius: 8px;
font-size: 15px;
}
pre.prettyprint {
width: 90%;
margin: 0.5em;
padding: 1em;
white-space: pre-wrap;
}
#return-to-top {
position: fixed;
bottom: 20px;
right: 20px;
background: rgb(0, 0, 0);
background: rgba(0, 0, 0, 0.2);
width: 50px;
height: 50px;
display: block;
text-decoration: none;
-webkit-border-radius: 35px;
-moz-border-radius: 35px;
border-radius: 35px;
display: none;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
#return-to-top i {
color: #fff;
margin: 0;
position: relative;
left: 16px;
top: 13px;
font-size: 19px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
#return-to-top:hover {
background: rgba(0, 0, 0, 0.35);
}
#return-to-top:hover i {
color: #f0f0f0;
}
@media print {
.pagebreak {
page-break-before: always;
}
div {
page-break-inside: avoid;
}
pre {
page-break-inside: avoid;
}
}
</style>
<body>
<header>
<aside>March 14, 2018</aside>
<a href="../" rel="author">Jure Šorn</a>
</header>
<a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
<div><h1 id="comprehensivepythoncheatsheet">Comprehensive Python Cheatsheet</h1><p class="banner"><sup><a href="https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md">Download text file</a>, <a href="https://github.com/gto76/python-cheatsheet">Fork me on GitHub</a> or <a href="https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions">Check out FAQ</a>.
</sup></p><p class="banner"><img src="web/image_888.jpeg" alt="Monty Python"></p><br><div><h2 id="toc"><a href="#toc" name="toc">#</a>Contents</h2><pre><code class="hljs bash"><strong>ToC</strong> = {
<strong><span class="hljs-string"><span class="hljs-string">'1. Collections'</span></span></strong>: [<a href="#list">List</a>, <a href="#dictionary">Dictionary</a>, <a href="#set">Set</a>, <a href="#tuple">Tuple</a>, <a href="#range">Range</a>, <a href="#enumerate">Enumerate</a>, <a href="#iterator">Iterator</a>, <a href="#generator">Generator</a>],
<strong><span class="hljs-string"><span class="hljs-string">'2. Types'</span></span></strong>: [<a href="#type">Type</a>, <a href="#string">String</a>, <a href="#regex">Regular_Exp</a>, <a href="#format">Format</a>, <a href="#numbers">Numbers</a>, <a href="#combinatorics">Combinatorics</a>, <a href="#datetime">Datetime</a>],
<strong><span class="hljs-string"><span class="hljs-string">'3. Syntax'</span></span></strong>: [<a href="#arguments">Args</a>, <a href="#inline">Inline</a>, <a href="#closure">Closure</a>, <a href="#decorator">Decorator</a>, <a href="#class">Class</a>, <a href="#ducktypes">Duck_Types</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exceptions</a>],
<strong><span class="hljs-string"><span class="hljs-string">'4. System'</span></span></strong>: [<a href="#print">Print</a>, <a href="#input">Input</a>, <a href="#commandlinearguments">Command_Line_Arguments</a>, <a href="#open">Open</a>, <a href="#path">Path</a>, <a href="#commandexecution">Command_Execution</a>],
<strong><span class="hljs-string"><span class="hljs-string">'5. Data'</span></span></strong>: [<a href="#csv">CSV</a>, <a href="#json">JSON</a>, <a href="#pickle">Pickle</a>, <a href="#sqlite">SQLite</a>, <a href="#bytes">Bytes</a>, <a href="#struct">Struct</a>, <a href="#array">Array</a>, <a href="#memoryview">MemoryView</a>, <a href="#deque">Deque</a>],
<strong><span class="hljs-string"><span class="hljs-string">'6. Advanced'</span></span></strong>: [<a href="#threading">Threading</a>, <a href="#operator">Operator</a>, <a href="#introspection">Introspection</a>, <a href="#metaprograming">Metaprograming</a>, <a href="#eval">Eval</a>, <a href="#coroutine">Coroutine</a>],
<strong><span class="hljs-string"><span class="hljs-string">'7. Libraries'</span></span></strong>: [<a href="#progressbar">Progress_Bar</a>, <a href="#plot">Plot</a>, <a href="#table">Table</a>, <a href="#curses">Curses</a>, <a href="#logging">Logging</a>, <a href="#scraping">Scraping</a>, <a href="#web">Web</a>, <a href="#profile">Profile</a>,
<a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#audio">Audio</a>]
}
</code></pre></div></div>
<div><h2 id="main"><a href="#main" name="main">#</a>Main</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>: <span class="hljs-comment"># Runs main() if file wasn't imported.</span>
main()
</code></pre></div>
<div><h2 id="list"><a href="#list" name="list">#</a>List</h2><pre><code class="python language-python hljs"><list> = <list>[from_inclusive : to_exclusive : ±step_size]
</code></pre></div>
<pre><code class="python language-python hljs"><list>.append(<el>) <span class="hljs-comment"># Or: <list> += [<el>]</span>
<list>.extend(<collection>) <span class="hljs-comment"># Or: <list> += <collection></span>
</code></pre>
<pre><code class="python language-python hljs"><list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
</code></pre>
<pre><code class="python language-python hljs">sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) <span class="hljs-keyword">for</span> pair <span class="hljs-keyword">in</span> zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=<span class="hljs-keyword">lambda</span> el: el[<span class="hljs-number">1</span>])
sorted_by_both = sorted(<collection>, key=<span class="hljs-keyword">lambda</span> el: (el[<span class="hljs-number">1</span>], el[<span class="hljs-number">0</span>]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out, x: out * x, <collection>)
list_of_chars = list(<str>)
</code></pre>
<pre><code class="python language-python hljs"><int> = <list>.count(<el>) <span class="hljs-comment"># Returns number of occurrences. Also works on strings.</span>
index = <list>.index(<el>) <span class="hljs-comment"># Returns index of first occurrence or raises ValueError.</span>
<list>.insert(index, <el>) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
<el> = <list>.pop([index]) <span class="hljs-comment"># Removes and returns item at index or from the end.</span>
<list>.remove(<el>) <span class="hljs-comment"># Removes first occurrence of item or raises ValueError.</span>
<list>.clear() <span class="hljs-comment"># Removes all items. Also works on dictionary and set.</span>
</code></pre>
<div><h2 id="dictionary"><a href="#dictionary" name="dictionary">#</a>Dictionary</h2><pre><code class="python language-python hljs"><view> = <dict>.keys() <span class="hljs-comment"># Coll. of keys that reflects changes.</span>
<view> = <dict>.values() <span class="hljs-comment"># Coll. of values that reflects changes.</span>
<view> = <dict>.items() <span class="hljs-comment"># Coll. of key-value tuples.</span>
</code></pre></div>
<pre><code class="python language-python hljs">value = <dict>.get(key, default=<span class="hljs-keyword">None</span>) <span class="hljs-comment"># Returns default if key does not exist.</span>
value = <dict>.setdefault(key, default=<span class="hljs-keyword">None</span>) <span class="hljs-comment"># Same, but also adds default to dict.</span>
<dict> = collections.defaultdict(<type>) <span class="hljs-comment"># Creates a dict with default value of type.</span>
<dict> = collections.defaultdict(<span class="hljs-keyword">lambda</span>: <span class="hljs-number">1</span>) <span class="hljs-comment"># Creates a dict with default value 1.</span>
</code></pre>
<pre><code class="python language-python hljs"><dict>.update(<dict>)
<dict> = dict(<collection>) <span class="hljs-comment"># Creates a dict from coll. of key-value pairs.</span>
<dict> = dict(zip(keys, values)) <span class="hljs-comment"># Creates a dict from two collections.</span>
<dict> = dict.fromkeys(keys [, value]) <span class="hljs-comment"># Creates a dict from collection of keys.</span>
</code></pre>
<pre><code class="python language-python hljs">value = <dict>.pop(key) <span class="hljs-comment"># Removes item or raises KeyError.</span>
{k: v <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> <dict>.items() <span class="hljs-keyword">if</span> k <span class="hljs-keyword">in</span> keys} <span class="hljs-comment"># Filters dictionary by keys.</span>
</code></pre>
<div><h3 id="counter">Counter</h3><pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> Counter
<span class="hljs-meta">>>> </span>colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>]
<span class="hljs-meta">>>> </span>counter = Counter(colors)
Counter({<span class="hljs-string">'blue'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'red'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'yellow'</span>: <span class="hljs-number">1</span>})
<span class="hljs-meta">>>> </span>counter.most_common()[<span class="hljs-number">0</span>]
(<span class="hljs-string">'blue'</span>, <span class="hljs-number">3</span>)
</code></pre></div>
<div><h2 id="set"><a href="#set" name="set">#</a>Set</h2><pre><code class="python language-python hljs"><set> = set()
</code></pre></div>
<pre><code class="python language-python hljs"><set>.add(<el>) <span class="hljs-comment"># Or: <set> |= {<el>}</span>
<set>.update(<collection>) <span class="hljs-comment"># Or: <set> |= <set></span>
</code></pre>
<pre><code class="python language-python hljs"><set> = <set>.union(<coll.>) <span class="hljs-comment"># Or: <set> | <set></span>
<set> = <set>.intersection(<coll.>) <span class="hljs-comment"># Or: <set> & <set></span>
<set> = <set>.difference(<coll.>) <span class="hljs-comment"># Or: <set> - <set></span>
<set> = <set>.symmetric_difference(<coll.>) <span class="hljs-comment"># Or: <set> ^ <set></span>
<bool> = <set>.issubset(<coll.>) <span class="hljs-comment"># Or: <set> <= <set></span>
<bool> = <set>.issuperset(<coll.>) <span class="hljs-comment"># Or: <set> >= <set></span>
</code></pre>
<pre><code class="python language-python hljs"><el> = <set>.pop() <span class="hljs-comment"># Raises KeyError if empty.</span>
<set>.remove(<el>) <span class="hljs-comment"># Raises KeyError if missing.</span>
<set>.discard(<el>) <span class="hljs-comment"># Doesn't raise an error.</span>
</code></pre>
<div><h3 id="frozenset">Frozen Set</h3><ul>
<li><strong>Is immutable and hashable.</strong></li>
<li><strong>That means it can be used as a key in a dictionary or as an element in a set.</strong></li>
</ul><pre><code class="python language-python hljs"><frozenset> = frozenset(<collection>)
</code></pre></div>
<div><h2 id="tuple"><a href="#tuple" name="tuple">#</a>Tuple</h2><p><strong>Tuple is an immutable and hashable list.</strong></p><pre><code class="python language-python hljs"><tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2>, ...)
</code></pre></div>
<div><h3 id="namedtuple">Named Tuple</h3><p><strong>Tuple's subclass with named elements.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
<span class="hljs-meta">>>> </span>Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
<span class="hljs-meta">>>> </span>p = Point(<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
<span class="hljs-meta">>>> </span>p[<span class="hljs-number">0</span>]
<span class="hljs-number">1</span>
<span class="hljs-meta">>>> </span>p.x
<span class="hljs-number">1</span>
<span class="hljs-meta">>>> </span>getattr(p, <span class="hljs-string">'y'</span>)
<span class="hljs-number">2</span>
<span class="hljs-meta">>>> </span>p._fields <span class="hljs-comment"># Or: Point._fields</span>
(<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>)
</code></pre></div>
<div><h2 id="range"><a href="#range" name="range">#</a>Range</h2><pre><code class="python language-python hljs"><range> = range(to_exclusive)
<range> = range(from_inclusive, to_exclusive)
<range> = range(from_inclusive, to_exclusive, ±step_size)
</code></pre></div>
<pre><code class="python language-python hljs">from_inclusive = <range>.start
to_exclusive = <range>.stop
</code></pre>
<div><h2 id="enumerate"><a href="#enumerate" name="enumerate">#</a>Enumerate</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">for</span> i, el <span class="hljs-keyword">in</span> enumerate(<collection> [, i_start]):
...
</code></pre></div>
<div><h2 id="iterator"><a href="#iterator" name="iterator">#</a>Iterator</h2><pre><code class="python language-python hljs"><iter> = iter(<collection>) <span class="hljs-comment"># `iter(<iter>)` returns unmodified iterator.</span>
<iter> = iter(<function>, to_exclusive) <span class="hljs-comment"># Sequence of return values until 'to_exclusive'.</span>
<el> = next(<iter> [, default]) <span class="hljs-comment"># Raises StopIteration or returns 'default' on end.</span>
</code></pre></div>
<div><h3 id="itertools">Itertools</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> count, repeat, cycle, chain, islice
</code></pre></div>
<pre><code class="python language-python hljs"><iter> = count(start=<span class="hljs-number">0</span>, step=<span class="hljs-number">1</span>) <span class="hljs-comment"># Returns incremented value endlessly.</span>
<iter> = repeat(<el> [, times]) <span class="hljs-comment"># Returns element endlessly or 'times' times.</span>
<iter> = cycle(<collection>) <span class="hljs-comment"># Repeats the sequence indefinitely.</span>
</code></pre>
<pre><code class="python language-python hljs"><iter> = chain(<coll.>, <coll.> [, ...]) <span class="hljs-comment"># Empties collections in order.</span>
<iter> = chain.from_iterable(<collection>) <span class="hljs-comment"># Empties collections inside a collection in order.</span>
</code></pre>
<pre><code class="python language-python hljs"><iter> = islice(<collection>, to_exclusive)
<iter> = islice(<collection>, from_inclusive, to_exclusive)
<iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)
</code></pre>
<div><h2 id="generator"><a href="#generator" name="generator">#</a>Generator</h2><ul>
<li><strong>Any function that contains a yield statement returns a generator.</strong></li>
<li><strong>Generators and iterators are interchangeable.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count</span><span class="hljs-params">(start, step)</span>:</span>
<span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
<span class="hljs-keyword">yield</span> start
start += step
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>counter = count(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>)
<span class="hljs-meta">>>> </span>next(counter), next(counter), next(counter)
(<span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>)
</code></pre>
<div><h2 id="type"><a href="#type" name="type">#</a>Type</h2><ul>
<li><strong>Everything is an object.</strong></li>
<li><strong>Every object has a type.</strong></li>
<li><strong>Type and class are synonymous.</strong></li>
</ul><pre><code class="python language-python hljs"><type> = type(<el>) <span class="hljs-comment"># Or: <el>.__class__</span>
<bool> = isinstance(<el>, <type>) <span class="hljs-comment"># Or: issubclass(type(<el>), <type>)</span>
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>type(<span class="hljs-string">'a'</span>), <span class="hljs-string">'a'</span>.__class__, str
(<<span class="hljs-class"><span class="hljs-title">class</span> '<span class="hljs-title">str</span>'>, <<span class="hljs-title">class</span> '<span class="hljs-title">str</span>'>, <<span class="hljs-title">class</span> '<span class="hljs-title">str</span>'>)
</span></code></pre>
<div><h4 id="sometypesdonothavebuiltinnamessotheymustbeimported">Some types do not have builtin names, so they must be imported:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> types <span class="hljs-keyword">import</span> FunctionType, MethodType, LambdaType, GeneratorType
</code></pre></div>
<div><h3 id="abc">ABC</h3><p><strong>An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> collections.abc <span class="hljs-keyword">import</span> Sequence, Collection, Iterable
<span class="hljs-meta">>>> </span>isinstance([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], Iterable)
<span class="hljs-keyword">True</span>
</code></pre></div>
<pre><code class="text language-text">+------------------+----------+------------+----------+
| | Sequence | Collection | Iterable |
+------------------+----------+------------+----------+
| list, range, str | yes | yes | yes |
| dict, set | | yes | yes |
| iter | | | yes |
+------------------+----------+------------+----------+
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> numbers <span class="hljs-keyword">import</span> Integral, Rational, Real, Complex, Number
<span class="hljs-meta">>>> </span>isinstance(<span class="hljs-number">123</span>, Number)
<span class="hljs-keyword">True</span>
</code></pre>
<pre><code class="text language-text">+--------------------+----------+----------+--------+---------+--------+
| | Integral | Rational | Real | Complex | Number |
+--------------------+----------+----------+--------+---------+--------+
| int | yes | yes | yes | yes | yes |
| fractions.Fraction | | yes | yes | yes | yes |
| float | | | yes | yes | yes |
| complex | | | | yes | yes |
| decimal.Decimal | | | | | yes |
+--------------------+----------+----------+--------+---------+--------+
</code></pre>
<div><h2 id="string"><a href="#string" name="string">#</a>String</h2><pre><code class="python language-python hljs"><str> = <str>.strip() <span class="hljs-comment"># Strips all whitespace characters from both ends.</span>
<str> = <str>.strip(<span class="hljs-string">'<chars>'</span>) <span class="hljs-comment"># Strips all passed characters from both ends.</span>
</code></pre></div>
<pre><code class="python language-python hljs"><list> = <str>.split() <span class="hljs-comment"># Splits on one or more whitespace characters.</span>
<list> = <str>.split(sep=<span class="hljs-keyword">None</span>, maxsplit=<span class="hljs-number">-1</span>) <span class="hljs-comment"># Splits on 'sep' str at most 'maxsplit' times.</span>
<list> = <str>.splitlines(keepends=<span class="hljs-keyword">False</span>) <span class="hljs-comment"># Splits on line breaks. Keeps them if 'keepends'.</span>
<str> = <str>.join(<coll_of_strings>) <span class="hljs-comment"># Joins elements using string as separator.</span>
</code></pre>
<pre><code class="python language-python hljs"><bool> = <sub_str> <span class="hljs-keyword">in</span> <str> <span class="hljs-comment"># Checks if string contains a substring.</span>
<bool> = <str>.startswith(<sub_str>) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
<bool> = <str>.endswith(<sub_str>) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
<int> = <str>.find(<sub_str>) <span class="hljs-comment"># Returns start index of first match or -1.</span>
<int> = <str>.index(<sub_str>) <span class="hljs-comment"># Same but raises ValueError.</span>
</code></pre>
<pre><code class="python language-python hljs"><str> = <str>.replace(old, new [, count]) <span class="hljs-comment"># Replaces 'old' with 'new' at most 'count' times.</span>
<bool> = <str>.isnumeric() <span class="hljs-comment"># True if str contains only numeric characters.</span>
<list> = textwrap.wrap(<str>, width) <span class="hljs-comment"># Nicely breaks string into lines.</span>
</code></pre>
<ul>
<li><strong>Also: <code class="python hljs"><span class="hljs-string">'lstrip()'</span></code>, <code class="python hljs"><span class="hljs-string">'rstrip()'</span></code>.</strong></li>
<li><strong>Also: <code class="python hljs"><span class="hljs-string">'lower()'</span></code>, <code class="python hljs"><span class="hljs-string">'upper()'</span></code>, <code class="python hljs"><span class="hljs-string">'capitalize()'</span></code> and <code class="python hljs"><span class="hljs-string">'title()'</span></code>.</strong></li>
</ul>
<div><h3 id="char">Char</h3><pre><code class="python language-python hljs"><str> = chr(<int>) <span class="hljs-comment"># Converts int to unicode char.</span>
<int> = ord(<str>) <span class="hljs-comment"># Converts unicode char to int.</span>
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>ord(<span class="hljs-string">'0'</span>), ord(<span class="hljs-string">'9'</span>)
(<span class="hljs-number">48</span>, <span class="hljs-number">57</span>)
<span class="hljs-meta">>>> </span>ord(<span class="hljs-string">'A'</span>), ord(<span class="hljs-string">'Z'</span>)
(<span class="hljs-number">65</span>, <span class="hljs-number">90</span>)
<span class="hljs-meta">>>> </span>ord(<span class="hljs-string">'a'</span>), ord(<span class="hljs-string">'z'</span>)
(<span class="hljs-number">97</span>, <span class="hljs-number">122</span>)
</code></pre>
<div><h2 id="regex"><a href="#regex" name="regex">#</a>Regex</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> re
<str> = re.sub(<regex>, new, text, count=<span class="hljs-number">0</span>) <span class="hljs-comment"># Substitutes all occurrences.</span>
<list> = re.findall(<regex>, text) <span class="hljs-comment"># Returns all occurrences.</span>
<list> = re.split(<regex>, text, maxsplit=<span class="hljs-number">0</span>) <span class="hljs-comment"># Use brackets in regex to keep the matches.</span>
<Match> = re.search(<regex>, text) <span class="hljs-comment"># Searches for first occurrence of pattern.</span>
<Match> = re.match(<regex>, text) <span class="hljs-comment"># Searches only at the beginning of the text.</span>
<iter> = re.finditer(<regex>, text) <span class="hljs-comment"># Returns all occurrences as match objects.</span>
</code></pre></div>
<ul>
<li><strong>Search() and match() return None if there are no matches.</strong></li>
<li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.IGNORECASE'</span></code> can be used with all functions.</strong></li>
<li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.MULTILINE'</span></code> makes <code class="python hljs"><span class="hljs-string">'^'</span></code> and <code class="python hljs"><span class="hljs-string">'$'</span></code> match the start/end of each line.</strong></li>
<li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.DOTALL'</span></code> makes dot also accept newline.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">r'\1'</span></code> or <code class="python hljs"><span class="hljs-string">'\\1'</span></code> for backreference.</strong></li>
<li><strong>Add <code class="python hljs"><span class="hljs-string">'?'</span></code> after an operator to make it non-greedy.</strong></li>
</ul>
<div><h3 id="matchobject">Match Object</h3><pre><code class="python language-python hljs"><str> = <Match>.group() <span class="hljs-comment"># Whole match. Also group(0).</span>
<str> = <Match>.group(<span class="hljs-number">1</span>) <span class="hljs-comment"># Part in first bracket.</span>
<tuple> = <Match>.groups() <span class="hljs-comment"># All bracketed parts.</span>
<int> = <Match>.start() <span class="hljs-comment"># Start index of a match.</span>
<int> = <Match>.end() <span class="hljs-comment"># Exclusive end index of a match.</span>
</code></pre></div>
<div><h3 id="specialsequences">Special Sequences</h3><ul>
<li><strong>By default digits, whitespaces and alphanumerics from all alphabets are matched, unless <code class="python hljs"><span class="hljs-string">'flags=re.ASCII'</span></code> argument is used.</strong></li>
<li><strong>Use capital letters for negation.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-string">'\d'</span> == <span class="hljs-string">'[0-9]'</span> <span class="hljs-comment"># Digit</span>
<span class="hljs-string">'\s'</span> == <span class="hljs-string">'[ \t\n\r\f\v]'</span> <span class="hljs-comment"># Whitespace</span>
<span class="hljs-string">'\w'</span> == <span class="hljs-string">'[a-zA-Z0-9_]'</span> <span class="hljs-comment"># Alphanumeric</span>
</code></pre></div>
<div><h2 id="format"><a href="#format" name="format">#</a>Format</h2><pre><code class="python language-python hljs"><str> = <span class="hljs-string">f'<span class="hljs-subst">{<el_1>}</span>, <span class="hljs-subst">{<el_2>}</span>'</span>
<str> = <span class="hljs-string">'{}, {}'</span>.format(<el_1>, <el_2>)
</code></pre></div>
<div><h3 id="attributes">Attributes</h3><pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
<span class="hljs-meta">>>> </span>Person = namedtuple(<span class="hljs-string">'Person'</span>, <span class="hljs-string">'name height'</span>)
<span class="hljs-meta">>>> </span>person = Person(<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)
<span class="hljs-meta">>>> </span><span class="hljs-string">f'<span class="hljs-subst">{person.height}</span>'</span>
<span class="hljs-string">'187'</span>
<span class="hljs-meta">>>> </span><span class="hljs-string">'{p.height}'</span>.format(p=person)
<span class="hljs-string">'187'</span>
</code></pre></div>
<div><h3 id="generaloptions">General Options</h3><pre><code class="python language-python hljs">{<el>:<<span class="hljs-number">10</span>} <span class="hljs-comment"># '<el> '</span>
{<el>:^<span class="hljs-number">10</span>} <span class="hljs-comment"># ' <el> '</span>
{<el>:><span class="hljs-number">10</span>} <span class="hljs-comment"># ' <el>'</span>
</code></pre></div>
<pre><code class="python language-python hljs">{<el>:.<<span class="hljs-number">10</span>} <span class="hljs-comment"># '<el>......'</span>
{<el>:><span class="hljs-number">0</span>} <span class="hljs-comment"># '<el>'</span>
</code></pre>
<div><h3 id="strings">Strings</h3><p><strong><code class="python hljs"><span class="hljs-string">'!r'</span></code> calls object's repr() method, instead of str(), to get a string.</strong></p><pre><code class="python language-python hljs">{<span class="hljs-string">'abcde'</span>!r:<<span class="hljs-number">10</span>} <span class="hljs-comment"># "'abcde' "</span>
{<span class="hljs-string">'abcde'</span>:<span class="hljs-number">.3</span>} <span class="hljs-comment"># 'abc'</span>
{<span class="hljs-string">'abcde'</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># 'abc '</span>
</code></pre></div>
<div><h3 id="numbers-1">Numbers</h3><pre><code class="python language-python hljs">{ <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>,} <span class="hljs-comment"># ' 123,456'</span>
{ <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>_} <span class="hljs-comment"># ' 123_456'</span>
{ <span class="hljs-number">123456</span>:+<span class="hljs-number">10</span>} <span class="hljs-comment"># ' +123456'</span>
{<span class="hljs-number">-123456</span>:=<span class="hljs-number">10</span>} <span class="hljs-comment"># '- 123456'</span>
{ <span class="hljs-number">123456</span>: } <span class="hljs-comment"># ' 123456'</span>
{<span class="hljs-number">-123456</span>: } <span class="hljs-comment"># '-123456'</span>
</code></pre></div>
<div><h3 id="floats">Floats</h3><pre><code class="python language-python hljs">{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># ' 1.23'</span>
{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>f} <span class="hljs-comment"># ' 1.235'</span>
{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>e} <span class="hljs-comment"># ' 1.235e+00'</span>
{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>%} <span class="hljs-comment"># ' 123.456%'</span>
</code></pre></div>
<div><h4 id="comparisonoffloatpresentationtypes">Comparison of float presentation types:</h4><pre><code class="text language-text">+----------------+----------------+---------------+----------------+-----------------+
| | {<float>} | {<float>:f} | {<float>:e} | {<float>:%} |
+----------------+----------------+---------------+----------------+-----------------+
| 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
| 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
| 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
| 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
| 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
| 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
| 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
| 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' |
+----------------+----------------+---------------+----------------+-----------------+
</code></pre></div>
<pre><code class="text language-text">+----------------+----------------+---------------+----------------+-----------------+
| | {<float>:.2} | {<float>:.2f} | {<float>:.2e} | {<float>:.2%} |
+----------------+----------------+---------------+----------------+-----------------+
| 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
| 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
| 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
| 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
| 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
| 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
| 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
| 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' |
+----------------+----------------+---------------+----------------+-----------------+
</code></pre>
<div><h3 id="ints">Ints</h3><pre><code class="python language-python hljs">{<span class="hljs-number">90</span>:c} <span class="hljs-comment"># 'Z'</span>
{<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'</span>
{<span class="hljs-number">90</span>:b} <span class="hljs-comment"># '1011010'</span>
</code></pre></div>
<div><h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2><div><h3 id="types">Types</h3><pre><code class="python language-python hljs"><int> = int(<float/str/bool>) <span class="hljs-comment"># Or: math.floor(<float>)</span>
<float> = float(<int/str/bool>)
<complex> = complex(real=<span class="hljs-number">0</span>, imag=<span class="hljs-number">0</span>) <span class="hljs-comment"># Or: <real> + <real>j</span>
<Fraction> = fractions.Fraction(numerator=<span class="hljs-number">0</span>, denominator=<span class="hljs-number">1</span>)
<Decimal> = decimal.Decimal(<int/float/str>)
</code></pre></div></div>
<ul>
<li><strong><code class="python hljs"><span class="hljs-string">'int(<str>)'</span></code> and <code class="python hljs"><span class="hljs-string">'float(<str>)'</span></code> raise ValueError on malformed strings.</strong></li>
<li><strong>Decimal numbers can be represented exactly, unlike floats where <code class="python hljs"><span class="hljs-string">'1.1 + 2.2 != 3.3'</span></code>.</strong></li>
<li><strong>Their precision can be adjusted with <code class="python hljs"><span class="hljs-string">'decimal.getcontext().prec = <int>'</span></code>.</strong></li>
</ul>
<div><h3 id="basicfunctions">Basic Functions</h3><pre><code class="python language-python hljs"><num> = pow(<num>, <num>) <span class="hljs-comment"># Or: <num> ** <num></span>
<num> = abs(<num>)
<int> = round(<num>)
<num> = round(<num>, ±ndigits) <span class="hljs-comment"># `round(126, -1) == 130`</span>
</code></pre></div>
<div><h3 id="math">Math</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> e, pi, inf, nan
<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians
<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2
</code></pre></div>
<div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, variance, pvariance, pstdev
</code></pre></div>
<div><h3 id="random">Random</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, choice, shuffle
<float> = random()
<int> = randint(from_inclusive, to_inclusive)
<el> = choice(<list>)
shuffle(<list>)
</code></pre></div>
<div><h3 id="binhex">Bin, Hex</h3><pre><code class="python language-python hljs"><int> = <span class="hljs-number">0</span>b<bin> <span class="hljs-comment"># Or: 0x<hex></span>
<int> = int(<span class="hljs-string">'<bin>'</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># Or: int('<hex>', 16)</span>
<int> = int(<span class="hljs-string">'0b<bin>'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int('0x<hex>', 0)</span>
<span class="hljs-string">'0b<bin>'</span> = bin(<int>) <span class="hljs-comment"># Or: '0x<hex>' = hex(<int>)</span>
</code></pre></div>
<div><h3 id="bitwiseoperators">Bitwise Operators</h3><pre><code class="python language-python hljs"><int> = <int> & <int> <span class="hljs-comment"># And</span>
<int> = <int> | <int> <span class="hljs-comment"># Or</span>
<int> = <int> ^ <int> <span class="hljs-comment"># Xor (0 if both bits equal)</span>
<int> = <int> << n_bits <span class="hljs-comment"># Shift left</span>
<int> = <int> >> n_bits <span class="hljs-comment"># Shift right</span>
<int> = ~<int> <span class="hljs-comment"># Compliment (flips bits)</span>
</code></pre></div>
<div><h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2><ul>
<li><strong>Every function returns an iterator.</strong></li>
<li><strong>If you want to print the iterator, you need to pass it to the list() function!</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> product, combinations, combinations_with_replacement, permutations
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>product([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>], repeat=<span class="hljs-number">3</span>)
[(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>)]
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>product(<span class="hljs-string">'ab'</span>, <span class="hljs-string">'12'</span>)
[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'2'</span>),
(<span class="hljs-string">'b'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'2'</span>)]
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>combinations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>)]
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>combinations_with_replacement(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
(<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
(<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)]
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>permutations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
(<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
(<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)]
</code></pre>
<div><h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2><ul>
<li><strong>Module 'datetime' provides 'date' <code class="apache hljs"><span class="hljs-section"><D></span></code>, 'time' <code class="apache hljs"><span class="hljs-section"><T></span></code>, 'datetime' <code class="apache hljs"><span class="hljs-section"><DT></span></code> and 'timedelta' <code class="apache hljs"><span class="hljs-section"><TD></span></code> classes. All are immutable and hashable.</strong></li>
<li><strong>Time and datetime can be 'aware' <code class="apache hljs"><span class="hljs-section"><a></span></code>, meaning they have defined timezone, or 'naive' <code class="apache hljs"><span class="hljs-section"><n></span></code>, meaning they don't.</strong></li>
<li><strong>If object is naive it is presumed to be in system's timezone.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date, time, datetime, timedelta
<span class="hljs-keyword">from</span> dateutil.tz <span class="hljs-keyword">import</span> UTC, tzlocal, gettz
</code></pre></div>
<div><h3 id="constructors">Constructors</h3><pre><code class="python language-python apache hljs"><D> = date(year, month, day)
<T> = time(hour=<span class="hljs-number">0</span>, minute=<span class="hljs-number">0</span>, second=<span class="hljs-number">0</span>, microsecond=<span class="hljs-number">0</span>, tzinfo=<span class="hljs-keyword">None</span>, fold=<span class="hljs-number">0</span>)
<DT> = datetime(year, month, day, hour=<span class="hljs-number">0</span>, minute=<span class="hljs-number">0</span>, second=<span class="hljs-number">0</span>, ...)
<TD> = timedelta(days=<span class="hljs-number">0</span>, seconds=<span class="hljs-number">0</span>, microseconds=<span class="hljs-number">0</span>, milliseconds=<span class="hljs-number">0</span>,
minutes=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>, weeks=<span class="hljs-number">0</span>)
</code></pre></div>
<ul>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week (Mon == 0).</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'fold=1'</span></code> means second pass in case of time jumping back for one hour.</strong></li>
</ul>
<div><h3 id="now">Now</h3><pre><code class="python language-python hljs"><D/DTn> = D/DT.today() <span class="hljs-comment"># Current local date or naive datetime.</span>
<DTn> = DT.utcnow() <span class="hljs-comment"># Naive datetime from current UTC time.</span>
<DTa> = DT.now(<tzinfo>) <span class="hljs-comment"># Aware datetime from current tz time.</span>
</code></pre></div>
<ul>
<li><strong>To extract time use <code class="python hljs"><span class="hljs-string">'<DTn>.time()'</span></code>, <code class="python hljs"><span class="hljs-string">'<DTa>.time()'</span></code> or <code class="python hljs"><span class="hljs-string">'<DTa>.timetz()'</span></code>.</strong></li>
</ul>
<div><h3 id="timezone">Timezone</h3><pre><code class="python language-python hljs"><tzinfo> = UTC <span class="hljs-comment"># UTC timezone. London without DST.</span>
<tzinfo> = tzlocal() <span class="hljs-comment"># Local timezone. Also gettz().</span>
<tzinfo> = gettz(<span class="hljs-string">'<Cont.>/<City>'</span>) <span class="hljs-comment"># 'Continent/City_Name' timezone or None.</span>
</code></pre></div>
<pre><code class="python language-python apache hljs"><DTa> = <DT>.astimezone(<tzinfo>) <span class="hljs-comment"># Datetime, converted to passed timezone.</span>
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) <span class="hljs-comment"># Unconverted object with new timezone.</span>
</code></pre>
<div><h3 id="encode">Encode</h3><pre><code class="python language-python apache hljs"><D/T/DT> = D/T/DT.fromisoformat(<span class="hljs-string">'<iso>'</span>) <span class="hljs-comment"># Object from ISO string. Raises ValueError.</span>
<DT> = DT.strptime(<str>, <span class="hljs-string">'<format>'</span>) <span class="hljs-comment"># Datetime from str, according to format.</span>
<D/DTn> = D/DT.fromordinal(<int>) <span class="hljs-comment"># D/DTn from days since Christ, at midnight.</span>
<DTn> = DT.fromtimestamp(<real>) <span class="hljs-comment"># Local time DTn from seconds since Epoch.</span>
<DTa> = DT.fromtimestamp(<real>, <tz.>) <span class="hljs-comment"># Aware datetime from seconds since Epoch.</span>
</code></pre></div>
<ul>
<li><strong>ISO strings come in following forms: <code class="python hljs"><span class="hljs-string">'YYYY-MM-DD'</span></code>, <code class="python hljs"><span class="hljs-string">'HH:MM:SS.ffffff[±<offset>]'</span></code>, or both separated by <code class="python hljs"><span class="hljs-string">'T'</span></code>. Offset is formatted as: <code class="python hljs"><span class="hljs-string">'HH:MM'</span></code>.</strong></li>
<li><strong>On Unix systems Epoch is <code class="python hljs"><span class="hljs-string">'1970-01-01 00:00 UTC'</span></code>, <code class="python hljs"><span class="hljs-string">'1970-01-01 01:00 CET'</span></code>, …</strong></li>
</ul>
<div><h3 id="decode">Decode</h3><pre><code class="python language-python hljs"><str> = <D/T/DT>.isoformat() <span class="hljs-comment"># ISO string representation.</span>
<str> = <D/T/DT>.strftime(<span class="hljs-string">'<format>'</span>) <span class="hljs-comment"># Custom string representation.</span>
<int> = <D/DT>.toordinal() <span class="hljs-comment"># Days since Christ, ignoring time and tz.</span>
<float> = <DTn>.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTn in local time.</span>
<float> = <DTa>.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTa.</span>
</code></pre></div>
<div><h3 id="format-1">Format</h3><pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
<span class="hljs-meta">>>> </span>dt = datetime.strptime(<span class="hljs-string">'2015-05-14 23:39:00.00 +0200'</span>, <span class="hljs-string">'%Y-%m-%d %H:%M:%S.%f %z'</span>)
<span class="hljs-meta">>>> </span>dt.strftime(<span class="hljs-string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)
<span class="hljs-string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span>
</code></pre></div>
<ul>
<li><strong>When parsing, <code class="python hljs"><span class="hljs-string">'%z'</span></code> also accepts <code class="python hljs"><span class="hljs-string">'±HH:MM'</span></code>.</strong></li>
<li><strong>For abbreviated weekday and month use <code class="python hljs"><span class="hljs-string">'%a'</span></code> and <code class="python hljs"><span class="hljs-string">'%b'</span></code>.</strong></li>
</ul>
<div><h3 id="arithmetics">Arithmetics</h3><pre><code class="python language-python apache hljs"><TD> = <D/DT> - <D/DT>
<D/DT> = <D/DT> ± <TD>
<TD> = <TD> ± <TD>
<TD> = <TD> */ <real>
</code></pre></div>
<div><h2 id="arguments"><a href="#arguments" name="arguments">#</a>Arguments</h2><div><h3 id="insidefunctioncall">Inside Function Call</h3><pre><code class="python language-python hljs"><function>(<positional_args>) <span class="hljs-comment"># f(0, 0)</span>
<function>(<keyword_args>) <span class="hljs-comment"># f(x=0, y=0)</span>
<function>(<positional_args>, <keyword_args>) <span class="hljs-comment"># f(0, y=0)</span>
</code></pre></div></div>
<div><h3 id="insidefunctiondefinition">Inside Function Definition</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(<nondefault_args>)</span>:</span> <span class="hljs-comment"># def f(x, y):</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(<default_args>)</span>:</span> <span class="hljs-comment"># def f(x=0, y=0):</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(<nondefault_args>, <default_args>)</span>:</span> <span class="hljs-comment"># def f(x, y=0):</span>
</code></pre></div>
<div><h2 id="splatoperator"><a href="#splatoperator" name="splatoperator">#</a>Splat Operator</h2><div><h3 id="insidefunctioncall-1">Inside Function Call</h3><p><strong>Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.</strong></p><pre><code class="python language-python hljs">args = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
kwargs = {<span class="hljs-string">'x'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'y'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'z'</span>: <span class="hljs-number">5</span>}
func(*args, **kwargs)
</code></pre></div></div>
<div><h4 id="isthesameas">Is the same as:</h4><pre><code class="python language-python hljs">func(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, x=<span class="hljs-number">3</span>, y=<span class="hljs-number">4</span>, z=<span class="hljs-number">5</span>)
</code></pre></div>
<div><h3 id="insidefunctiondefinition-1">Inside Function Definition</h3><p><strong>Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.</strong></p><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(*a)</span>:</span>
<span class="hljs-keyword">return</span> sum(a)
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-number">6</span>
</code></pre>
<div><h4 id="legalargumentcombinations">Legal argument combinations:</h4><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*, x, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, y, *, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span>
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args)</span>:</span> <span class="hljs-comment"># f(1, 2, 3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args)</span>:</span> <span class="hljs-comment"># f(1, 2, 3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, z)</span>:</span> <span class="hljs-comment"># f(1, 2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, z)</span>:</span> <span class="hljs-comment"># f(1, 2, z=3)</span>
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(**kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*, x, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, y, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, z, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span>
</code></pre>
<div><h3 id="otheruses">Other Uses</h3><pre><code class="python language-python hljs"><list> = [*<collection> [, ...]]
<set> = {*<collection> [, ...]}
<tuple> = (*<collection>, [...])
<dict> = {**<dict> [, ...]}
</code></pre></div>
<pre><code class="python language-python hljs">head, *body, tail = <collection>
</code></pre>
<div><h2 id="inline"><a href="#inline" name="inline">#</a>Inline</h2><div><h3 id="lambda">Lambda</h3><pre><code class="python language-python hljs"><function> = <span class="hljs-keyword">lambda</span>: <return_value>
<function> = <span class="hljs-keyword">lambda</span> <argument_1>, <argument_2>: <return_value>
</code></pre></div></div>
<div><h3 id="comprehension">Comprehension</h3><pre><code class="python language-python hljs"><list> = [i+<span class="hljs-number">1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)] <span class="hljs-comment"># [1, 2, ..., 10]</span>
<set> = {i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>) <span class="hljs-keyword">if</span> i > <span class="hljs-number">5</span>} <span class="hljs-comment"># {6, 7, 8, 9}</span>
<iter> = (i+<span class="hljs-number">5</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (5, 6, ..., 14)</span>
<dict> = {i: i*<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)} <span class="hljs-comment"># {0: 0, 1: 2, ..., 9: 18}</span>
</code></pre></div>
<pre><code class="python language-python hljs">out = [i+j <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>) <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)]
</code></pre>
<div><h4 id="isthesameas-1">Is the same as:</h4><pre><code class="python language-python hljs">out = []
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
<span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
out.append(i+j)
</code></pre></div>
<div><h3 id="mapfilterreduce">Map, Filter, Reduce</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> reduce
<iter> = map(<span class="hljs-keyword">lambda</span> x: x + <span class="hljs-number">1</span>, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (1, 2, ..., 10)</span>
<iter> = filter(<span class="hljs-keyword">lambda</span> x: x > <span class="hljs-number">5</span>, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (6, 7, 8, 9)</span>
<obj> = reduce(<span class="hljs-keyword">lambda</span> out, x: out + x, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># 45</span>
</code></pre></div>
<div><h3 id="anyall">Any, All</h3><pre><code class="python language-python hljs"><bool> = any(<collection>) <span class="hljs-comment"># False if empty.</span>
<bool> = all(el[<span class="hljs-number">1</span>] <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> <collection>) <span class="hljs-comment"># True if empty.</span>
</code></pre></div>
<div><h3 id="ifelse">If - Else</h3><pre><code class="python language-python hljs"><expression_if_true> <span class="hljs-keyword">if</span> <condition> <span class="hljs-keyword">else</span> <expression_if_false>
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>[a <span class="hljs-keyword">if</span> a <span class="hljs-keyword">else</span> <span class="hljs-string">'zero'</span> <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>)]
[<span class="hljs-string">'zero'</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'zero'</span>, <span class="hljs-number">3</span>]
</code></pre>
<div><h3 id="namedtupleenumdataclass">Namedtuple, Enum, Dataclass</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
point = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
Direction = Enum(<span class="hljs-string">'Direction'</span>, <span class="hljs-string">'n e s w'</span>)
direction = Direction.n
</code></pre>
<pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
Creature = make_dataclass(<span class="hljs-string">'Creature'</span>, [<span class="hljs-string">'location'</span>, <span class="hljs-string">'direction'</span>])
creature = Creature(Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), Direction.n)
</code></pre>
<div><h2 id="closure"><a href="#closure" name="closure">#</a>Closure</h2><p><strong>We have a closure in Python when:</strong></p><ul>
<li><strong>A nested function references a value of its enclosing function and then</strong></li>
<li><strong>the enclosing function returns the nested function.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_multiplier</span><span class="hljs-params">(a)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(b)</span>:</span>
<span class="hljs-keyword">return</span> a * b
<span class="hljs-keyword">return</span> out
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>multiply_by_3 = get_multiplier(<span class="hljs-number">3</span>)
<span class="hljs-meta">>>> </span>multiply_by_3(<span class="hljs-number">10</span>)
<span class="hljs-number">30</span>
</code></pre>
<ul>
<li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
<li><strong>To dynamically access function's first free variable use <code class="python hljs"><span class="hljs-string">'<function>.__closure__[0].cell_contents'</span></code>.</strong></li>
</ul>
<div><h3 id="partial">Partial</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial
<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
<span class="hljs-meta">>>> </span>multiply_by_3 = partial(op.mul, <span class="hljs-number">3</span>)
<span class="hljs-meta">>>> </span>multiply_by_3(<span class="hljs-number">10</span>)
<span class="hljs-number">30</span>
</code></pre>
<ul>
<li><strong>Partial is also useful in cases when a function needs to be passed as an argument, because it enables us to set its arguments beforehand.</strong></li>
<li><strong>A few examples being <code class="python hljs"><span class="hljs-string">'defaultdict(<function>)'</span></code>, <code class="python hljs"><span class="hljs-string">'iter(<function>, to_exclusive)'</span></code> and dataclass's <code class="python hljs"><span class="hljs-string">'field(default_factory=<function>)'</span></code>.</strong></li>
</ul>
<div><h3 id="nonlocal">Nonlocal</h3><p><strong>If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.</strong></p><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_counter</span><span class="hljs-params">()</span>:</span>
i = <span class="hljs-number">0</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">()</span>:</span>
<span class="hljs-keyword">nonlocal</span> i
i += <span class="hljs-number">1</span>
<span class="hljs-keyword">return</span> i
<span class="hljs-keyword">return</span> out
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>counter = get_counter()
<span class="hljs-meta">>>> </span>counter(), counter(), counter()
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<div><h2 id="decorator"><a href="#decorator" name="decorator">#</a>Decorator</h2><p><strong>A decorator takes a function, adds some functionality and returns it.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">@decorator_name</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_that_gets_passed_to_decorator</span><span class="hljs-params">()</span>:</span>
...
</code></pre></div>
<div><h3 id="debuggerexample">Debugger Example</h3><p><strong>Decorator that prints function's name every time it gets called.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(func)</span>:</span>
<span class="hljs-meta"> @wraps(func)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
print(func.__name__)
<span class="hljs-keyword">return</span> func(*args, **kwargs)
<span class="hljs-keyword">return</span> out
<span class="hljs-meta">@debug</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
<span class="hljs-keyword">return</span> x + y
</code></pre></div>
<ul>
<li><strong>Wraps is a helper decorator that copies metadata of function add() to function out().</strong></li>
<li><strong>Without it <code class="python hljs"><span class="hljs-string">'add.__name__'</span></code> would return <code class="python hljs"><span class="hljs-string">'out'</span></code>.</strong></li>
</ul>
<div><h3 id="lrucache">LRU Cache</h3><p><strong>Decorator that caches function's return values. All function's arguments must be hashable.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache
<span class="hljs-meta">@lru_cache(maxsize=None)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>
<span class="hljs-keyword">return</span> n <span class="hljs-keyword">if</span> n < <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> fib(n-<span class="hljs-number">2</span>) + fib(n-<span class="hljs-number">1</span>)
</code></pre></div>
<ul>
<li><strong>Recursion depth is limited to 1000 by default. To increase it use <code class="python hljs"><span class="hljs-string">'sys.setrecursionlimit(<depth>)'</span></code>.</strong></li>
</ul>
<div><h3 id="parametrizeddecorator">Parametrized Decorator</h3><p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(print_result=False)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>
<span class="hljs-meta"> @wraps(func)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
result = func(*args, **kwargs)
print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>)
<span class="hljs-keyword">return</span> result
<span class="hljs-keyword">return</span> out
<span class="hljs-keyword">return</span> decorator
<span class="hljs-meta">@debug(print_result=True)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
<span class="hljs-keyword">return</span> x + y
</code></pre></div>
<div><h2 id="class"><a href="#class" name="class">#</a>Class</h2><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <<span class="hljs-title">name</span>>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
self.a = a
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span><span class="hljs-params">(self)</span>:</span>
class_name = self.__class__.__name__
<span class="hljs-keyword">return</span> <span class="hljs-string">f'<span class="hljs-subst">{class_name}</span>(<span class="hljs-subst">{self.a!r}</span>)'</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
<span class="hljs-keyword">return</span> str(self.a)
<span class="hljs-meta"> @classmethod</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_class_name</span><span class="hljs-params">(cls)</span>:</span>
<span class="hljs-keyword">return</span> cls.__name__
</code></pre></div>
<ul>
<li><strong>Return value of repr() should be unambiguous and of str() readable.</strong></li>
<li><strong>If only repr() is defined, it will be also used for str().</strong></li>
</ul>
<div><h4 id="strusecases">Str() use cases:</h4><pre><code class="python language-python hljs">print(<el>)
print(<span class="hljs-string">f'<span class="hljs-subst">{<el>}</span>'</span>)
<span class="hljs-keyword">raise</span> Exception(<el>)
loguru.logger.debug(<el>)
csv.writer(<file>).writerow([<el>])
</code></pre></div>
<div><h4 id="reprusecases">Repr() use cases:</h4><pre><code class="python language-python hljs">print([<el>])
print(<span class="hljs-string">f'<span class="hljs-subst">{<el>!r}</span>'</span>)
<span class="hljs-meta">>>> </span><el>
loguru.logger.exception()
Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span class="hljs-string">'a'</span>]); print(Z(<el>))
</code></pre></div>
<div><h3 id="constructoroverloading">Constructor Overloading</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <<span class="hljs-title">name</span>>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a=None)</span>:</span>
self.a = a
</code></pre></div>
<div><h3 id="inheritance">Inheritance</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, age)</span>:</span>
self.name = name
self.age = age
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Person)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, age, staff_num)</span>:</span>
super().__init__(name, age)
self.staff_num = staff_num
</code></pre></div>
<div><h3 id="multipleinheritance">Multiple Inheritance</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span>:</span> <span class="hljs-keyword">pass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>:</span> <span class="hljs-keyword">pass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span><span class="hljs-params">(A, B)</span>:</span> <span class="hljs-keyword">pass</span>
</code></pre></div>
<p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong></p>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>C.mro()
[<<span class="hljs-class"><span class="hljs-title">class</span> '<span class="hljs-title">C</span>'>, <<span class="hljs-title">class</span> '<span class="hljs-title">A</span>'>, <<span class="hljs-title">class</span> '<span class="hljs-title">B</span>'>, <<span class="hljs-title">class</span> '<span class="hljs-title">object</span>'>]
</span></code></pre>
<div><h3 id="property">Property</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>:</span>
<span class="hljs-meta"> @property</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
<span class="hljs-keyword">return</span> self._a
<span class="hljs-meta"> @a.setter</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self, value)</span>:</span>
self._a = value
</code></pre></div>
<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>el = MyClass()
<span class="hljs-meta">>>> </span>el.a = <span class="hljs-number">123</span>
<span class="hljs-meta">>>> </span>el.a
<span class="hljs-number">123</span>
</code></pre>
<div><h3 id="dataclass">Dataclass</h3><p><strong>Decorator that automatically generates init(), repr() and eq() special methods.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass, field
<span class="hljs-meta">@dataclass(order=False, frozen=False)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <<span class="hljs-title">class_name</span>>:</span>
<attr_name_1>: <type>
<attr_name_2>: <type> = <default_value>
<attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
</code></pre></div>
<ul>
<li><strong>An object can be made sortable with <code class="python hljs"><span class="hljs-string">'order=True'</span></code> or immutable with <code class="python hljs"><span class="hljs-string">'frozen=True'</span></code>.</strong></li>
<li><strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">'<attr_name>: list = []'</span></code> would make a list that is shared among all instances.</strong></li>
<li><strong>Default_factory can be any <a href="#callable">callable</a>.</strong></li>
</ul>
<div><h3 id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClassWithSlots</span>:</span>
__slots__ = [<span class="hljs-string">'a'</span>]
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
self.a = <span class="hljs-number">1</span>
</code></pre></div>