-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathREADME.md
1806 lines (1480 loc) · 58.5 KB
/
README.md
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
# Python Standard Libraries Cheatsheet
Depend on Python v3.9.8
All code snippets have been tested to ensure they work properly.
Fork me on [GitHub](https://github.com/pynickle/python-cheatsheet).
- [中文](README-zh-cn.md)
- [English](README.md)
**Notes**:
- **Every code snippet here can run independently (some need the files provided by this repo)**
- **You can get a version of the page with switchable code themes and languages from the flask project in the web folder**
- **You can use GETREADME.py to download README.md from the repository (Chinese or English, with or not with command line prefixes is up to you!)**
## Contents
**Text Processing**: [``string``](#string), [``re``](#re), [``difflib``](#difflib),
[``textwrap``](#textwrap), [``unicodedata``](#unicodedata), [``readline``](#readline)
**Binary Data**: [``codecs``](#codecs), [``struct``](#struct)
**Data Type**: [``datetime``](#datetime), [``calendar``](#calendar), [``collections``](#collections),[``copy``](#copy), [``pprint``](#pprint), [``enum``](#enum), [``bisect``](#bisect), [``heapq``](#heapq), [``weakref``](#weakref)
**Mathematical Modules**: [``math``](#math), [``cmath``](#cmath), [``random``](#random),
[``fractions``](#fractions), [``decimal``](#decimal), [``statistics``](#statistics)
**Functional Programming**: [``itertools``](#itertools), [``functools``](#functools), [``operator``](#operator)
**Directory Access**: [``pathlib``](#pathlib), [``os.path``](#os.path), [``glob``](#glob), [``tempfile``](#tempfile),
[``filecmp``](#filecmp), [``fileinput``](#fileinput), [``shutil``](#shutil), [``linecache``](#linecache)
**Data Persistence**: [``pickle``](#pickle), [``copyreg``](#copyreg)
**Data Compression**: [``zlib``](#zlib), [``lzma``](#lzma), [``zipfile``](#zipfile)
**File Formats**: [``configparser``](#configparser)
**Cryptographic Services**: [``hashlib``](#hashlib), [``hmac``](#hmac), [``secrets``](#secrets)
**Operating System**: [``os``](#os), [``time``](#time), [``logging``](#logging),
[``getpass``](#getpass), [``platform``](#platform), [``argparse``](#argparse),
[``errno``](#errno), [``io``](#io)
**Networking Communication**: [``socket``](#socket)
**Internet Data**: [``json``](#json)
**Structured Markup**: [``html``](#html)
**Internet Protocols**: [``webbrowser``](#webbrowser)
**Multimedia Services**: [``wave``](#wave), [``sndhdr``](#sndhdr), [``imghdr``](#imghdr),
[``colorsys``](#colorsys)
**Program Frameworks**: [``turtle``](#turtle)
**Graphical Interfaces**: [``tkinter``](#tkinter)
**Development Tools**: [``typing``](#typing), [``doctest``](#doctest)
**Debugging Profiling**: [``timeit``](#timeit), [``pdb``](#pdb)
**Software Packaging**: [``ensurepip``](#ensurepip), [``zipapp``](#zipapp)
**Runtime Services**: [``sys``](#sys), [``dataclasses``](#dataclasses),
[``contextlib``](#contextlib), [``abc``](#abc), [``traceback``](#traceback),
[``__future__``](#__future__), [``atexit``](#atexit), [``builtins``](#builtins),
[``inspect``](#inspect)
**Importing Modules**: [``zipimport``](#zipimport), [``importlib``](#importlib), [``runpy``](#runpy)
**Language Services**: [``ast``](#ast), [``keyword``](#keyword), [``dis``](#dis), [``tabnanny``](#tabnanny)
**Bonus Scene**: [``this``](#this), [``antigravity``](#antigravity)
## string
#### Attributes
```python
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.whitespace
' \t\n\r\x0b\x0c'
```
#### Formatter
```python
>>> import string
>>> formatter = string.Formatter()
>>> strcmp = "my name is {name}"
>>> dct = {"name": "nick"}
>>> formatter.format(strcmp, **dct) # use dict to format
'my name is nick'
>>> data = ("3",) # add , to make it a tuple
>>> strcmp = "pi is about {}"
>>> formatter.format(strcmp, *data) # use tuple to format
'pi is about 3'
```
#### Template
```python
>>> import string
>>> strcmp = "Hello $World" # the default delimiter is $
>>> t = string.Template(strcmp)
>>> t.substitute({"World": "nick"}) # use dict
'Hello nick'
>>> t.substitute(World = "nick") # use args
'Hello nick'
>>> class MyTemplate(string.Template):
... delimiter = "^"
...
>>> strcmp = "Hello ^World"
>>> mytemplate = MyTemplate(strcmp)
>>> mytemplate.substitute(World = "nick")
'Hello nick'
```
## re
#### match, search, findall
```python
>>> import re
>>> strcmp = "www.baidu.com"
>>> re.match("www", strcmp).span() # span function to get index
(0, 3)
>>> re.match("baidu", strcmp) # re.match only match from the beginning of the string
>>> re.search("baidu", strcmp).span() # re.search search from all string and return the first
(4, 9)
>>> strcmp = "baidu.com/runoob.com"
>>> re.findall("com", strcmp) # re.findall find all results and return
['com', 'com']
>>> re.findall("b(.*?).", strcmp)
['', '']
>>> re.findall("b(.*?)c", strcmp)
['aidu.', '.']
```
#### split, sub, escape
```python
>>> import re
>>> re.split(r"\W", "hello,world") # use regular expression
['hello', 'world']
>>> re.sub(r"Boy|Girl", "Human", "boy and girl", flags = re.I) # re.I means ignoring apitalization
'Human and Human'
>>> re.escape(r"#$&*+-.^|~")
'\\#\\$\\&\\*\\+\\-\\.\\^\\|\\~'
```
## difflib
#### Differ
```python
>>> import difflib
>>> d = difflib.Differ()
>>> text1 = """difflib
... python version 3.7.4
... difflib version 3.7.4
... this is difflib document
... """
>>> text2 = """difflib
... python version 3.7.3
... this is difflib document
... feature: diff in linux
... """
>>> text1_lines = text1.splitlines()
>>> text2_lines = text2.splitlines()
>>>
>>> list(d.compare(text1_lines, text2_lines))
[' difflib', '- python version 3.7.4', '? ^\n', '+ python version 3.7.3', '? ^\n', '- difflib version 3.7.4', ' this is difflib document', '+ feature: diff in linux']
```
#### HtmlDiff
```python
>>> import difflib
>>> d = difflib.HtmlDiff()
>>> text1 = """difflib
... python version 3.7.4
... difflib version 3.7.4
... this is difflib document
... """
>>> text2 = """difflib
... python version 3.7.3
... this is difflib document
... feature: diff in linux
... """
>>> text1_lines = text1.splitlines()
>>> text2_lines = text2.splitlines()
>>> with open("HtmlDiff.html", "w", encoding="utf-8") as f: # make it a html file
... HtmlDiff = d.make_file(text1_lines, text2_lines)
... f.write(HtmlDiff)
...
3331
```
#### SequenceMatcher
```python
>>> import difflib
>>> s = difflib.SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
>>> s = difflib.SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
>>> s = difflib.SequenceMatcher(None, "abcd", "abd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=1), Match(a=4, b=3, size=0)]
```
## textwrap
#### wrap, fill, shorten, dedent, indent
```python
>>> import textwrap
>>> strcmp = "Hello,World! My name is nick, l am 14 years old"
>>> textwrap.wrap(strcmp, width = 10) # 10 for an element
['Hello,Worl', 'd! My name', 'is nick, l', 'am 14', 'years old']
>>> textwrap.fill(strcmp, width = 10)
'Hello,Worl\nd! My name\nis nick, l\nam 14\nyears old'
>>> textwrap.shorten(strcmp, width = 45) # content over 45 will be [...]
'Hello,World! My name is nick, l am 14 [...]'
>>> textwrap.shorten(strcmp, width = 45, placeholder = "...") # change the placeholder
'Hello,World! My name is nick, l am 14...'
>>> strcmp = """
... hello world!
... """
>>> textwrap.dedent(strcmp)
'\nhello world!\n'
>>> strcmp = """Hello World!
... l am nick.
... l am 14 years old.
... """
>>> textwrap.indent(strcmp, " + ", lambda line: True)
' + Hello World!\n + l am nick.\n + l am 14 years old.\n'
```
## unicodedata
#### lookup, name, unidata_version
```python
>>> import unicodedata
>>> unicodedata.lookup('LEFT CURLY BRACKET') # get the symbol of the description
'{'
>>> unicodedata.name("(") # reverse to lookup
'LEFT PARENTHESIS'
>>> unicodedata.unidata_version
'13.0.0'
```
## readline
#### parse_and_bind
**Notice**: If you are using Windows, you need to first install pyreadline module:
```bash
pip install pyreadline
```
```python
>>> import readline
>>> readline.parse_and_bind('tab: complete') # use tab to autocomplete
>>> histfile = '.pythonhistory'
```
## codecs
#### encode, decode, getencoder, getdecoder
```python
>>> import codecs
>>> codecs.encode("你好")
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> codecs.decode(b"\xe4\xbd\xa0\xe5\xa5\xbd")
'你好'
>>> codecs.getencoder("utf-8")
<built-in function utf_8_encode>
>>> codecs.getdecoder("gbk")
<built-in method decode of MultibyteCodec object at 0x0000019E080AA078>
```
## struct
#### pack, unpack
**Notice**: The format is on [struct docs](#https://docs.python.org/3/library/struct.html)
```python
>>> import struct
>>> struct.pack(">l", 1024) # return a bytes containing the values packed according to the format string format
b'\x00\x00\x04\x00'
>>> struct.unpack(">lH", b'\x00\x00\x04\x00\xf0\xf0')
(1024, 61680)
```
## datetime
#### MINYEAR, MAXYEAR, date
More Information about strftime is on [strftime docs](#https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)
```python
>>> import datetime
>>> datetime.MINYEAR
1
>>> datetime.MAXYEAR
9999
>>> date = datetime.date
>>> date.today()
datetime.date(2019, 7, 21)
>>> date = datetime.date(2019, 7, 21)
>>> date.today()
datetime.date(2019, 7, 21)
>>> date.weekday()
6
>>> date.isocalendar()
(2019, 29, 7)
>>> date.ctime()
'Sun Jul 21 00:00:00 2019'
>>> date.strftime("%Y %d %y, %H:%M:%S")
'2019 21 19, 00:00:00'
```
## calendar
#### isleap, firstweekday, month
```python
>>> import calendar
>>> calendar.isleap(2000) # check if it is leap year
True
>>> calendar.firstweekday()
0
>>> print(calendar.month(2019, 7)) # get the pretty calendar
July 2019
Mo Tu We Th Fr Sa Su
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
```
## collections
#### namedtuple, deque, defaultdict, OrderedDict, Counter
```python
>>> import collections
>>> point = collections.namedtuple("point", ["x", "y"]) # create tuple subclasses with named fields
>>> p = point(2, 1)
>>> p.x, p.y
(2, 1)
>>> deque = collections.deque(["b", "c", "d"]) # list-like container with fast appends and pops on either end
>>> deque.appendleft("a") # much faster than original list
>>> deque.append("e")
>>> deque
deque(['a', 'b', 'c', 'd', 'e'])
>>> dd = collections.defaultdict(lambda: "None") # dict which has an default value
>>> dd ["key-1"] = "value-1"
>>> dd["key-1"]
'value-1'
>>> dd["key-2"] # if the key is not exist, it will return the default value instead of raising an error
'None'
>>> od = collections.OrderedDict([("a", 1), ("b", 2)]) # dict which always keeps the order
>>> od
OrderedDict([('a', 1), ('b', 2)])
>>> c = collections.Counter() # dict subclass for counting hashable objects
>>> for i in "Hello, World":
... c[i] = c[i] + 1
...
>>> c
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
```
## copy
#### copy, deepcopy
```python
>>> import copy
>>> origin = [1, 2, [3, 4]]
>>> copy1 = copy.copy(origin)
>>> copy2 = copy.deepcopy(origin)
>>> copy1 is copy2
False
>>> origin[2][0] = "Hello, copy"
>>> copy1 # change when origin changes
[1, 2, ['Hello, copy', 4]]
>>> copy2 # don't change when origin changes
[1, 2, [3, 4]]
```
## pprint
#### pprint
```python
>>> import pprint # pretty print
>>> strcmp = ("hello world", {"nick": 13, "ben": 12}, (1, 2, 3, 4), [5, 6, 7, 8], "Hello pprint")
>>> pprint.pprint(strcmp)
('hello world',
{'ben': 12, 'nick': 13},
(1, 2, 3, 4),
[5, 6, 7, 8],
'Hello pprint')
```
## enum
#### Enum, unique, auto
```python
>>> import enum
>>> class Seasons(enum.Enum):
... Spring = 1
... Summer = 2
... Autumn = 3
... Winter = 4
...
>>> Seasons.Spring
<Seasons.Spring: 1>
>>> @enum.unique # don't allow same value
... class Unique(enum.Enum):
... Nick = 13
... Ben = 12
... Jack = 13
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python38\lib\enum.py", line 860, in unique
raise ValueError('duplicate values found in %r: %s' %
ValueError: duplicate values found in <enum 'Unique'>: Jack -> Nick
>>> class Auto(enum.Enum):
... VS = enum.auto()
... VSCode = enum.auto()
... Pycharm = enum.auto()
...
>>> list(Auto) # auto is from one
[<Auto.VS: 1>, <Auto.VSCode: 2>, <Auto.Pycharm: 3>]
```
## bisect
#### bisect, bisect_left, bisect_right, insort, insort_left, insort_right
```python
>>> import bisect
>>> a = [1, 2, 4, 5]
>>> bisect.bisect_left(a, 1) # if it has the same, choose left
0
>>> bisect.bisect_right(a, 1) # if it has the same, choose right
1
>>> bisect.bisect(a, 1)
1
>>> bisect.insort(a, 1) # bisect and insert
>>> a
[1, 1, 2, 4, 5]
>>> bisect.insort_left(a, 2)
>>> a
[1, 1, 2, 2, 4, 5]
>>> bisect.insort_right(a, 4)
>>> a
[1, 1, 2, 2, 4, 4, 5]
```
## heapq
#### heappush, heappop
```python
>>> import heapq
>>> def heapsort(iterable):
... h = []
... for i in iterable:
... heapq.heappush(h, i) # first push all numbers
... return [heapq.heappop(h) for i in range(len(h))] # it was orderly extracted
...
>>> heapsort([4, 3, 6, 9, 1, 7])
[1, 3, 4, 6, 7, 9]
```
## weakref
#### ref
```python
>>> import weakref
>>> class A:
... def method():
... print("A")
...
>>> def b(reference):
... print(reference)
...
>>> c = A()
>>> d = weakref.ref(c, b) # when c is deleted, b is called
>>> del c
<weakref at 0x000001C94E12F778; dead>
```
## math
#### ceil, factorial, floor, modf, log, pow, sqrt, pi, e
```python
>>> import math
>>> math.ceil(1.4) # return the smallest integer greater than or equal to x
2
>>> math.factorial(5)
120
>>> math.floor(1.6) # return the largest integer less than or equal to x
1
>>> math.modf(1.6) # return the fractional and integer parts
(0.6000000000000001, 1.0)
>>> math.log(8)
2.0794415416798357
>>> math.pow(2,5) # pow in math produces float type number, pow in builtin function produces int type number
32.0
>>> math.sqrt(9)
3.0
>>> math.pi # equal to π
3.141592653589793
>>> math.e # constant e's value
2.718281828459045
```
## cmath
#### sin, tan, cos
```python
>>> import cmath # complex maths
>>> cmath.sin(7)
(0.6569865987187891+0j)
>>> cmath.tan(7)
(0.8714479827243188+0j)
>>> cmath.cos(7)
(0.7539022543433046-0j)
```
## random
#### random, uniform, randint, randrange
```python
>>> import random
>>> random.random() # from 0 to 1
0.6381052887323486
>>> random.uniform(5,6) # from x to y
5.325285695528384
>>> random.randint(6, 9) # include nine
9
>>> random.randrange(5, 10) # don't include ten
9
```
## fractions
#### Fraction, limit_denominator
```python
>>> import fractions
>>> fractions.Fraction(16, -10)
Fraction(-8, 5)
>>> fractions.Fraction("-16/10")
Fraction(-8, 5)
>>> fractions.Fraction(8, 5) - fractions.Fraction(7, 5) # fractions can do substraction
Fraction(1, 5)
>>> fractions.Fraction(1.1) # sometimes it will be strange
Fraction(2476979795053773, 2251799813685248)
>>> fractions.Fraction(1.1).limit_denominator() # use limit denominator to get right fraction
Fraction(11, 10)
>>> import math
>>> math.floor(fractions.Fraction(5, 3)) # it can also be combined with math module
1
```
## decimal
#### Decimal, getcontext
```python
>>> import decimal
>>> decimal.Decimal(2)/decimal.Decimal(3)
Decimal('0.6666666666666666666666666667')
>>> context = decimal.getcontext()
>>> context
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])
>>> context.prec = 5
>>> x = decimal.Decimal(2)/decimal.Decimal(3)
>>> x
Decimal('0.66667')
>>> x.sqrt()
Decimal('0.81650')
>>> x.log10()
Decimal('-0.17609')
```
## statistics
#### mean, harmonic_mean, median, median_low, median_high
```python
>>> import statistics
>>> statistics.mean([1, 2, 3])
2
>>> statistics.harmonic_mean([2, 5, 10])
3.75
>>> statistics.median([2, 3, 5, 6]) # get the median of these numbers, median can not be in it
4.0
>>> statistics.median_low([2, 3, 5, 6]) # median must be in it and get the lower median
3
>>> statistics.median_high([2, 3, 5, 6]) # get the higher median
5
```
## itertools
#### count, repeat, groupby
```python
>>> import itertools # itertools always return a iterator
>>> for i in zip(itertools.count(1), ["A", "B", "C"]):
... print(i)
...
(1, 'A')
(2, 'B')
(3, 'C')
>>> for i in itertools.repeat("Hello Repeat!", 5):
... print(i)
...
Hello Repeat!
Hello Repeat!
Hello Repeat!
Hello Repeat!
Hello Repeat!
>>> [list(g) for k, g in itertools.groupby('AAAABBBCCD')]
[['A', 'A', 'A', 'A'], ['B', 'B', 'B'], ['C', 'C'], ['D']]
```
## functools
#### lru_cache, reduce
```python
>>> import functools
>>> @functools.lru_cache(None) # None means the cache's upper limit is not limited
... def fibonacci(n):
... if n<2:
... return n
... return fibonacci(n-1) + fibonacci(n-2)
...
>>> fibonacci(10)
55
>>> def add(a, b):
... return a+b
...
>>> functools.reduce(add, range(1,100)) # add from 1 to 100
4950
```
## operator
#### lt, eq, le, ne, gt, ge, abs, pow, concat, contains, indexOf, add
```python
>>> import operator # substitute for builtin operator
>>> operator.lt(3, 4) # 3<4
True
>>> operator.eq(3, 4) # 3=4
False
>>> operator.le(3, 4) # 3<=4
True
>>> operator.ne(3, 4) # 3!=4
True
>>> operator.gt(3, 4) # 3>4
False
>>> operator.ge(3, 4) # 3>=4
False
>>> operator.abs(-10)
10
>>> operator.pow(10, 2)
100
>>> operator.concat("a", "b")
'ab'
>>> operator.contains([1, 2, 3], 2)
True
>>> operator.indexOf([1, 2, 3, 2, 1], 2)
1
>>> operator.add(1, 2)
3
```
## pathlib
#### Path
```python
>>> import pathlib
>>> p = pathlib.Path(".")
>>> list(p.glob('**/*.py'))
[WindowsPath('GETREADME.py'), WindowsPath('test.py')]
>>> p/"dir" # use / to get further path
WindowsPath('dir')
>>> (p/"GETREADME.py").name
'GETREADME.py'
>>> p.is_absolute()
False
```
## os.path
#### exists, getsize, isfile, isdir, join
```python
>>> import os.path
>>> os.path.exists(".")
True
>>> os.path.getsize("./LICENSE")
466
>>> os.path.isfile("./README.md")
True
>>> os.path.isdir("./doc")
False
>>> os.path.join("./doc", "tutorial", "basic") # join the directory and file
'./doc\\tutorial\\basic'
```
## glob
#### glob
```python
>>> import glob
>>> glob.glob("*.pdf", recursive = True)
['README-zh-cn.pdf', 'README.pdf']
```
## tempfile
#### TemporaryFile, mkstemp, mkdtemp
```python
>>> import tempfile
>>> with tempfile.TemporaryFile() as f:
... f.write(b"a")
... f.seek(0)
... f.read()
...
1
0
b'a'
>>> name = tempfile.mkstemp() # for temporary file
>>> name
(3, 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp___ejm5a')
>>> with open(name[1], "w", encoding="utf-8") as f:
... f.write("Hello tempfile!")
...
15
>>> name = tempfile.mkdtemp() # for temporary dir
>>> name
'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp5mqb0bxz'
>>> with open(name + "\\temp.txt", "w", encoding="utf-8") as f:
... f.write("Hello tempfile!")
...
15
```
## filecmp
#### cmp
```python
>>> import filecmp
>>> filecmp.cmp("examples/cmp1.txt", "examples/cmp2.txt")
True
```
## fileinput
#### input
```python
>>> import os
>>> cmd = os.popen("python examples/fileinput_example.py examples/cmp1.txt") # subprocess.Popen provides more features
>>> print(cmd.read())
examples/cmp1.txt | Line Number: 1 |: 1
examples/cmp1.txt | Line Number: 2 |: 2
examples/cmp1.txt | Line Number: 3 |: 3
examples/cmp1.txt | Line Number: 4 |: 4
examples/cmp1.txt | Line Number: 5 |: 5
```
## shutil
#### copyfile, rmtree, move
```python
>>> import shutil
>>> shutil.copyfile("examples/song.wav", "examples/copysong.wav")
'examples/copysong.wav'
>>> shutil.rmtree("shutil_tree") # can delete tree has contents, os.remove can't
>>> shutil.move("examples/copysong.wav", "myapp/copysong.wav")
'myapp/copysong.wav'
```
## linecache
#### getline
```python
>>> import linecache
>>> linecache.getline("examples/GETREADME.py", 1) # start from one, not zero
'from sys import exit\n'
```
## pickle
#### loads, dumps
```python
>>> import pickle # pickle is a python-specific compression method
>>> data = [[1, "first"],
... [2, "second"]]
>>> dumps = pickle.dumps(data) # similar to json module
>>> dumps
b'\x80\x04\x95"\x00\x00\x00\x00\x00\x00\x00]\x94(]\x94(K\x01\x8c\x05first\x94e]\x94(K\x02\x8c\x06second\x94ee.'
>>> pickle.loads(dumps)
[[1, 'first'], [2, 'second']]
```
## copyreg
#### pickle
```python
>>> import copyreg
>>> import copy
>>> import pickle
>>> class A:
... def __init__(self, a):
... self.a = a
...
>>> def pickle_a(a):
... print("pickle A")
... return A, (a.a,)
...
>>> copyreg.pickle(A, pickle_a)
>>> a = A(1)
>>> b = copy.copy(a)
pickle A
>>>
>>> c = pickle.dumps(a)
pickle A
```
## zlib
#### compress, decompress
```python
>>> import zlib
>>> zlib.compress(b"Hello World!", 5)
b'x^\xf3H\xcd\xc9\xc9W\x08\xcf/\xcaIQ\x04\x00\x1cI\x04>'
>>> zlib.decompress(b'x^\xf3H\xcd\xc9\xc9W\x08\xcf/\xcaIQ\x04\x00\x1cI\x04>')
b'Hello World!'
```
## lzma
#### compress, decompress
```python
>>> import lzma
>>> lzma.compress(b"Hello, python3!")
b"\xfd7zXZ\x00\x00\x04\xe6\xd6\xb4F\x02\x00!\x01\x16\x00\x00\x00t/\xe5\xa3\x01\x00\x0eHello, python3!\x00\x00(\x92K\xe6\x9b\xe7r&\x00\x01'\x0f\xdf\x1a\xfcj\x1f\xb6\xf3}\x01\x00\x00\x00\x00\x04YZ"
>>> lzma.decompress(b"\xfd7zXZ\x00\x00\x04\xe6\xd6\xb4F\x02\x00!\x01\x16\x00\x00\x00t/\xe5\xa3\x01\x00\x0eHello, python3!\x00\x00(\x92K\xe6\x9b\xe7r&\x00\x01'\x0f\xdf\x1a\xfcj\x1f\xb6\xf3}\x01\x00\x00\x00\x00\x04YZ")
b'Hello, python3!'
```
## zipfile
#### ZipFile
```python
>>> import zipfile
>>> with zipfile.ZipFile("examples/g.zip") as f: # extract zip file
... f.extractall()
...
>>> with zipfile.ZipFile("a.zip", "a") as zip: # create zip file
... zip.write("README.md") # use write method to write files into zip file
...
```
## configparser
#### ConfigParser
```python
>>> import configparser
>>> config = configparser.ConfigParser() # create an instance
>>> config.read("examples/config.ini")
['examples/config.ini']
>>> config.sections()
['python', 'java']
>>> config["python"]["type"] # all sections has values in DEFAULT
'programming language'
>>> config["java"]["popular"]
'1'
```
## hashlib
#### md5
```python
>>> import hashlib
>>> md5 = hashlib.md5()
>>> md5.update(b"Hello World") # use update method to join in batches
>>> md5.block_size
64
>>> md5.digest_size
16
>>> md5.hexdigest()
'b10a8db164e0754105b7a99be72e3fe5'
>>> md5.digest()
b'\xb1\n\x8d\xb1d\xe0uA\x05\xb7\xa9\x9b\xe7.?\xe5'
```
## hmac
#### new, compare_digest
```python
>>> import hmac
>>> msg = b"Hello World"
>>> secret = b"key" # use key to encrypt
>>> h = hmac.new(secret, msg, digestmod='md5')
>>> h.hexdigest()
'432c3ea3b9a503183f3d1258d9016a0c'
>>> h.digest()
b'C,>\xa3\xb9\xa5\x03\x18?=\x12X\xd9\x01j\x0c'
>>> h2 = hmac.new(secret, b"Hello world", digestmod="md5")
>>> hmac.compare_digest(h.digest(), h2.digest())
False
```
## secrets
#### choice, token_bytes, token_hex
```python
>>> import secrets
>>> secrets.choice("Hello World!") # choose one character from the string
'd'
>>> secrets.token_bytes(32)
b'\xd7\x98\xba\xc5\x18[/\xeaLx\xdb\x962\x84\xff`(7&\xe6\xae\xd4\x17n,\xc3\x9e\xb0V\x1c\x1d\x99'
>>> secrets.token_hex(16)
'335f8df0cb6dd60a3c41fdba7ccd1a0b'
```
## os
#### name, getcwd
```python