Python Frequently Asked Questions: Guido Van Rossum and The Python Development Team
Python Frequently Asked Questions: Guido Van Rossum and The Python Development Team
3.13.3
27, 2025
1 Python 1
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 1
1.1.1 Python . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 1
1.1.2 Python . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 1
1.1.3 Python . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 1
1.1.4 Python . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 2
1.1.5 Python . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 2
1.1.6 Python . . . . . . .
. . . . . . . . . . . . . . . . . . . . 2
1.1.7 Python . . .
. . . . . . . . . . . . . . . . . . . . 3
1.1.8 Python . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 3
1.1.9 Python . . . . . . . . . . . . . . . . . . . 3
1.1.10 Python . . . . . . . . . . . . . . . . . . . . 3
1.1.11 Python . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.12 Python . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.13 Python . . . . . . . . . . . . 3
1.1.14 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.15 www.python.org . . . . . . . . . . . . . . . . . . . . . 4
1.1.16 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.17 ”Monty Python ” . . . . . . . . . . . . . . . . . . . . . 4
1.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.3 Python . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.4 Python . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.5 Python . . . . . . . . . . . . . . . . . . . . . . 5
1.2.6 Python . . . . . . . . . . . . . . . . . . . . . . 5
2 7
2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1 Python . . . . . . . . . . 7
2.1.2 . . . . . . . . . . . . . . . . . . . 7
2.1.3 Python . . . . . . . . . . . . . . . . . . 8
2.1.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.1 UnboundLocalError . . . . . . . . . . . . . . . . 8
2.2.2 Python . . . . . . . . . . . . . . . . . . . . . . 9
2.2.3 lambda . . . . . . . . . . . 9
2.2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.7 . . . . . . . . . . . 12
i
2.2.8 . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 12
2.2.9 ’y’ ’x’ . . . . . . . . . . . . .. . . . . . . . . . . . . 12
2.2.10 . . . . . .. . . . . . . . . . . . . 13
2.2.11 Python . . . . . . . . . . . . . . .. . . . . . . . . . . . . 14
2.2.12 Python . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 15
2.2.13 . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 15
2.2.14 . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 15
2.2.15 . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 16
2.2.16 C ”?:” . . . . . .. . . . . . . . . . . . . 16
2.2.17 Python ? . . . . . . . .. . . . . . . . . . . . . 16
2.2.18 / . . . . . . . . . .. . . . . . . . . . . . . 17
2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 17
2.3.1 . . . . . . . . . . . . . .. . . . . . . . . . . . . 17
2.3.2 -22 // 10 -3 . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 17
2.3.3 int SyntaxError . . . . . . . .. . . . . . . . . . . . . 18
2.3.4 . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 18
2.3.5 . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 18
2.3.6 . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 18
2.3.7 / . . . . . . . . . . . . . . .. . . . . . . . . . . . . 19
2.3.8 Perl chomp() . . . . . . . . . . 19
2.3.9 scanf() sscanf() . . . . . . . . . . . . . . . . . . . . . . . 20
2.3.10 UnicodeDecodeError UnicodeEncodeError . . . . . . . 20
2.3.11 . . . . . . . . . . . . . . . . . . . 20
2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.2 . . . . . . . . . . . . . . . . . . . 21
2.5 / . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.6 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.8 . . . . . . . . . . . . . . . . . 23
2.5.9 a_tuple[i] += [’item’] . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.10 Python . . . . . . . . . . . . . . 25
2.5.11 . . . . . . . . . . . . . . . . . . . . . 25
2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.3 self . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.4 . . . . . . . . . . . . . . . . . . 26
2.6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.6.6 . . . . . . . . . . . . . . . . . 27
2.6.7 . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.6.8 . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.6.9 Python . . . . . . . . . . . . . . . . . . . . . . 28
2.6.10 __spam _SomeClassName__spam . . . . . . 29
2.6.11 __del__ . . . . . . . . . . . . . . . . 29
2.6.12 . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.6.13 id() . . . . . . . . . . . . . . . . . . . . . . . . 30
2.6.14 is . . . . . . . . . . . . . 30
2.6.15 . . . . . . . . . . . . . 31
2.6.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.7.1 .pyc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
ii
2.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.7.4 __import__(’x.y.z’) <module ’x’> z . . . . . . . . . . . . 34
2.7.5 . . 35
3 37
3.1 Python . . .. . . .
. . . . . . . . . . . . . . . . . . . . . . . 37
3.2 .. . . .
. . . . . . . . . . . . . . . . . . . . . . . 37
3.3 . . . . . . . . . .. . . .
. . . . . . . . . . . . . . . . . . . . . . . 37
3.4 Python . . . . .. . . .
. . . . . . . . . . . . . . . . . . . . . . . 38
3.5 self . . . . . . . . . . . . . . . . . . . . . . . 38
3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7 Python list.index() len(List)
. . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . 39
3.8 join() . . . . . . . . . . . . . . . . . . . 39
3.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.10 Python switch case . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.11 . . . . . . . . 40
3.12 lambda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.13 Python C . . . . . . . . . . . . . . . . . . . . . . 41
3.14 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.15 CPython . . . . . . . . . . . . . . . . . . . . . . . . 41
3.16 CPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.18 CPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.19 CPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.20 key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.21 list.sort() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.22 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.23 goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.24 r-strings . . . . . . . . . . . . . . . . . . . . . . 44
3.25 Python with . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.26 with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.27 if/while/def/class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.28 Python . . . . . . . . . . . . . . . . . . . . . . 46
4 FAQ 47
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.1.1 X . . . . . . . . . . . . . . . . . . . . . . 47
4.1.2 math.py socket.py regex.py . . . . . . . . . . . . . . . . . . . 47
4.1.3 Unix Python . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.1.4 Python curses/termcap . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.1.5 Python C onexit() . . . . . . . . . . . . . . . . . . . . 48
4.1.6 . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.2.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.2.2 docstring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.4.1 . . . . . . . . . . . . . . . . . . . 52
4.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.4.4 os.popen() os.read() . . . . . . . . . . . . 53
iii
4.4.5 RS232 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.4.6 sys.stdout stdin stderr . . . . . . . . . . . . . . 53
4.5 / Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.1 Python WWW . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.2 HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.4 socket connect() . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.6.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.6.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.7.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5 / 57
5.1 C . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 57
5.2 C++ . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 57
5.3 C . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 57
5.4 C Python . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 57
5.5 C Python . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 57
5.6 Python C . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . 58
5.7 Py_BuildValue() . . . . . . . . . . . .
. . . . . . . . . . . . 58
5.8 C . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 58
5.9 PyErr_Print() stdout / stderr . . . . . . . . . . . 58
5.10 C Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.11 Python C ++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.12 Setup make . . . . . . . . . . . . . . . . . . 59
5.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.14 Linux Python ? . . . . . . . . . . 60
5.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.16 g++ __builtin_new __pure_virtual . . . . . . . . . . . . . . . . . 60
5.17 C Python
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
6 Python Windows 61
6.1 Windows Python . . . . .
. . . . . . . . . . . . . . . . . . . . . 61
6.2 Python . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . 62
6.3 Python . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . 62
6.4 Python . . . . . . .
. . . . . . . . . . . . . . . . . . . . . 62
6.5 *.pyd DLL . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . 62
6.6 Python Windows . . . . . .
. . . . . . . . . . . . . . . . . . . . . 62
6.7 Python tab . . . . . . . . . . . . . . . . . . . . . 63
6.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6.9 api-ms-win-crt-runtime-l1-1-0.dll . . . . . . . . . . . . . . . . . . . 64
7 GUI 65
7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.2 Python GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.3 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.3.1 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.3.2 I/O Tk . . . . . . . . . . . . . . . . . . . . . . . . 65
7.3.3 Tkinter . . . . . . . . . . . . . . . . . . . . . . . . . 65
8 Python 67
8.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
8.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
8.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
A 69
iv
B 85
B.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
C 87
C.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
C.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . 88
C.2.1 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 . . . . . . . . . . . . . 88
C.2.2 PYTHON 2.0 BEOPEN.COM . . . . . . . . . . . . . . . . . . . . . 89
C.2.3 PYTHON 1.6.1 CNRI . . . . . . . . . . . . . . . . . . . . . . . . . 89
C.2.4 PYTHON 0.9.0 1.2 CWI . . . . . . . . . . . . . . . . . . . . . . 90
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION . 91
C.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
C.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
C.3.4 Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
C.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
C.3.6 UUencode UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
C.3.7 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
C.3.9 Select kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
C.3.11 strtod dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
C.3.18 W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
C.3.19 mimalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
C.3.21 Global Unbounded Sequences (GUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
D 105
107
v
vi
CHAPTER 1
Python
1.1
1.1.1 Python
Python
Python
C
C++ Python
Linux macOS Unix Windows
tutorial-index Python Python
1.1.2 Python
Python Python Software Foundation PSF Python
2.1 PSF Python Python
PSF https://www.python.org/psf/
PSF Python PSF
1.1.3 Python
Python
Python
Python Python Python
PSF
Python
1
Python Frequently Asked Questions, 3.13.3
1.1.4 Python
Guido van Rossum :
CWI ABC
Python
Python
ABC ABC
ABC Amoeba
Amoeba
1989
Python Amoeba
1991 2 USENET
Misc/HISTORY
1.1.5 Python
Python
Unicode
HTTP, FTP, SMTP, XML-RPC, POP, IMAP
Python TCP/IP
library-index Python
1.1.6 Python
Python ”A.B.C” ”A.B”:
• A --
• B --
• C --
2 Chapter 1. Python
Python Frequently Asked Questions, 3.13.3
+ 2.2+ CPython
a0
2.4a0
Developer’s Guide PEP 387 Python
sys.version, sys.hexversion sys.version_info
1.1.7 Python
Python python.org https://www.python.org/downloads/
https://github.com/python/cpython/
gzip tar C Sphinx Python
UNIX
Python
1.1.8 Python
Python https://docs.python.org/3/ https://docs.python.org/3/
download.html PDF HTML
reStructuredText Sphinx reStructuredText Python
1.1.9 Python
tutorial-index
Python
1.1.10 Python
comp.lang.python python-list
comp.lang.python
Usenet
comp.lang.python.announce
python-announce
https://www.python.org/community/lists/
1.1.11 Python
https://www.python.org/downloads/ alpha beta comp.lang.python
comp.lang.python.announce Python https://www.python.org/ RSS
1.1.12 Python
https://github.com/python/cpython/issues
Python Python
1.1.13 Python
Python
Python 1991
Guido van Rossum Jelke de Boer, ” Python ”, CWI
, 4 , 4 (1991 12 ), , 283--303
1.1. 3
Python Frequently Asked Questions, 3.13.3
1.1.14 Python
python.org wiki https://wiki.python.org/moin/
PythonBooks
”Python” Monty Python ”Python”
”language”
1.1.15 www.python.org
Python Python
1.1.16 Python
Python Guido van Rossum ”Monty Python ”
1970 BBC Van Rossum
Python
1.2 Python
1.2.1 Python
1991 6 18
3.9 Python 12 (PEP 602)
3.5.3, 3.6.2
1.2.2 Python
Python
Linux
comp.lang.python Python
1.2.3 Python
https://www.python.org/about/success Python Python
1.2.4 Python
https://peps.python.org/ Python PEP PEP Python
”Python X.Y Release
Schedule” PEP X.Y
python-dev
4 Chapter 1. Python
Python Frequently Asked Questions, 3.13.3
1.2.5 Python
Python
Python
PEP 5
1.2.6 Python
PyGame
Python
:
>>> L = []
>>> dir(L)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> [d for d in dir(L) if '__' not in d]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
,→ 'sort']
>>> help(L.append)
Help on built-in function append:
append(...)
L.append(object) -> None -- append object to end
>>> L.append(1)
>>> L
[1]
1.2. Python 5
Python Frequently Asked Questions, 3.13.3
Python edu-sig
6 Chapter 1. Python
CHAPTER 2
2.1
2.1.1 Python
Python breakpoint()
pdb Python Python
pdb
Python IDLE ( Tools/scripts/idle3)
2.1.2
Pylint Pyflakes
Mypy, Pyre Pytype Python
7
Python Frequently Asked Questions, 3.13.3
2.1.3 Python
Python Python
C Python
import Python
Python C marshal
C Python
Python
GUI :
• Nuitka
• PyInstaller ( )
• PyOxidizer
• cx_Freeze
• py2app macOS
• py2exe ( Windows)
2.1.4 Python
PEP 8
2.2
2.2.1 UnboundLocalError
UnboundLocalError
>>> x = 10
>>> def bar():
... print(x)
...
>>> bar()
10
>>> x = 10
>>> def foo():
... print(x)
... x += 1
UnboundLocalError :
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
8 Chapter 2.
Python Frequently Asked Questions, 3.13.3
foo x
print(x)
>>> x = 10
>>> def foobar():
... global x
... print(x)
... x += 1
...
>>> foobar()
10
>>> print(x)
11
nonlocal
2.2.2 Python
Python
global
global global
global
2.2.3 lambda
for lambda
>>> squares = []
>>> for x in range(5):
... squares.append(lambda: x**2)
5 lambda x**2
0 1 4 9 16 16
>>> squares[2]()
16
>>> squares[4]()
16
2.2. 9
Python Frequently Asked Questions, 3.13.3
x lambda x lambda
x 4 4**2 16
x lambda
>>> x = 8
>>> squares[2]()
64
lambda x
>>> squares = []
>>> for x in range(5):
... squares.append(lambda n=x: n**2)
lambda
2.2.4
config cfg
config
config.py
x = 0 # 'x'
mod.py
import config
config.x = 1
main.py
import config
import mod
print(config.x)
2.2.5
from modulename import * importer
Linter
1. sys os argparse re
3.
10 Chapter 2.
Python Frequently Asked Questions, 3.13.3
Gordon McMillan
”import <module>” 2
1 ”from module import name”
1 1
2
2
1 2
sys.modules
2.2.6
Bug
def foo(mydict={}): #
... ...
mydict[key] = value
return mydict
None
None
None
def foo(mydict={}):
...
def foo(mydict=None):
if mydict is None:
mydict = {} #
memoize
# _cache
def expensive(arg1, arg2, *, _cache={}):
if (arg1, arg2) in _cache:
return _cache[(arg1, arg2)]
#
result = ... ...
_cache[(arg1, arg2)] = result #
return result
2.2. 11
Python Frequently Asked Questions, 3.13.3
2.2.7
* **
* **
2.2.8
42 314 somevar
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
y x
1) y = x
y x x y
2) mutable
append() [] [10]
[10]
>>> x = 5 #
>>> y = x
>>> x = x + 1 # 5
>>> x
6
>>> y
5
x y immutable x = x + 1
5 1 6 x x
12 Chapter 2.
Python Frequently Asked Questions, 3.13.3
6 5 x 6
y 5
( y.append(10) y.sort()) ( y = y
+ [10] sorted(y) <sorted>) Python ( )
``None`()
y.sort() y None
is id()
2.2.10
Python
1)
2)
3)
4) :
2.2. 13
Python Frequently Asked Questions, 3.13.3
5)
2.2.11 Python
linear(a,b) a*x+b
f(x)
class linear:
taxes = linear(0.3, 2)
class exponential(linear):
# __init__
def __call__(self, x):
return self.a * (x ** self.b)
class counter:
value = 0
14 Chapter 2.
Python Frequently Asked Questions, 3.13.3
( )
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1
count = counter()
inc, dec, reset = count.up, count.down, count.set
2.2.12 Python
copy.copy() copy.deepcopy()
copy()
newdict = olddict.copy()
new_l = l[:]
2.2.13
x dir(x)
2.2.14
def class
>>> class A:
... pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x16D07CC>
>>> print(a)
<__main__.A object at 0x16D07CC>
B
A a b
2.2. 15
Python Frequently Asked Questions, 3.13.3
2.2.15
Python
= +=
2.2.16 C ”?:”
x, y = 50, 25
small = x if x < y else y
Python 2.5
on_true ... if
... else ...
2.2.17 Python ?
lambda lambda Ulf Bartelt
:
# < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
# 10
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))
#
print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\n'+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
# \___ ___/ \___ ___/ | | |__
# V V | |______
# | | |__________
# | |_________________ y
# |____________________________ x
16 Chapter 2.
Python Frequently Asked Questions, 3.13.3
2.2.18 /
divmod()
:
>>> help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
divmod()
2.3
2.3.1
”o”
”a” ”10” 8
>>> a = 0o10
>>> a
8
”x”
Python
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
2.3.2 -22 // 10 -3
i % j j
i == (i // j) * j + (i % j)
C i // j
i % j i
i % j j j
i % j >= 0 10 200 -190
% 12 == 2 -190 % 12 == -10
2.3. 17
Python Frequently Asked Questions, 3.13.3
>>> 1.__class__
File "<stdin>", line 1
1.__class__
^
SyntaxError: invalid decimal literal
>>> 1 .__class__
<class 'int'>
>>> (1).__class__
<class 'int'>
2.3.4
int() int('144') == 144 float()
float('144') == 144.0
int('0144') == 144 int('0x144')
ValueError int(string, base) int( '0x144',
16) == 324 0 Python ’0o’ ’0x’
eval() eval()
Python __import__('os').system("rm -rf
$HOME") home
eval() Python eval('09') Python
’0’ ’0’
2.3.5
144 '144' str()
hex() oct() f-strings formatstrings
"{:04d}".format(144) '0144' "{:.3f}".format(1.0/3.0) '0.333'
2.3.6
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'
18 Chapter 2.
Python Frequently Asked Questions, 3.13.3
( )
>>> print(a)
array('w', 'yello, world')
>>> a.tounicode()
'yello, world'
2.3.7 /
•
case
def a():
pass
def b():
pass
dispatch[get_input()]() #
• getattr()
import foo
getattr(foo, 'bar')()
getattr()
class Foo:
def do_foo(self):
...
def do_bar(self):
...
• locals()
def myFunc():
print("hello")
fname = "myFunc"
f = locals()[fname]
f()
2.3. 19
Python Frequently Asked Questions, 3.13.3
S.rstrip()
split()
int() float() split() ”sep”
C sscanf
2.3.11
:
>>> r'C:\this\will\not\work\'
File "<stdin>", line 1
r'C:\this\will\not\work\'
^
SyntaxError: unterminated string literal (detected at line 1)
>>> 'C:\\this\\will\\work\\'
'C:\\this\\will\\work\\'
Windows os.path.join() :
>>> r'backslash\'preserved'
"backslash\\'preserved"
2.4
2.4.1
• timeit
20 Chapter 2.
Python Frequently Asked Questions, 3.13.3
Python
•
• bltin-types collections
•
C
list.sort() sorted() sortinghowto
•
Python Cython
Python C Cython
C
C
wiki
2.4.2
str bytes
str str.join()
chunks = []
for s in my_strings:
chunks.append(s)
result = ''.join(chunks)
io.StringIO
bytes bytearray +=
result = bytearray()
for b in my_bytes_objects:
result += b
2.5 /
2.5.1
tuple(seq)
tuple()
list(seq) list((1,
2, 3)) [1, 2, 3] list('abc') ['a', 'b', 'c']
seq[:]
2.5. / 21
Python Frequently Asked Questions, 3.13.3
2.5.2
Python 0 1
-1 -2 seq[-n]
seq[len(seq)-n]
S[:-1]
2.5.3
reversed()
for x in reversed(sequence):
... # x ...
2.5.4
Python Cookbook
https://code.activestate.com/recipes/52560/
if mylist:
mylist.sort()
last = mylist[-1]
for i in range(len(mylist)-2, -1, -1):
if last == mylist[i]:
del mylist[i]
else:
last = mylist[i]
hashable
mylist = list(set(mylist))
2.5.5
2.5.6 Python
C Pascal Python
array
NumPy
22 Chapter 2.
Python Frequently Asked Questions, 3.13.3
Lisp cons :
2.5.7
>>> A = [[None] * 2] * 3
>>> A
[[None, None], [None, None], [None, None]]
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
* *3 3
2 1
A = [None] * 3
for i in range(3):
A[i] = [None] * 2
3 2
w, h = 2, 3
A = [[None] * w for i in range(h)]
NumPy
2.5.8
list comprehension :
for :
2.5. / 23
Python Frequently Asked Questions, 3.13.3
list +=
:
1 1 a_tuple[0] 2
2 0
>>> a_tuple[0]
['foo', 'item']
(a) __iadd__()
+= (b) __iadd__()
extend() += list.extend()
:
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
a_list a_list
a_list
24 Chapter 2.
Python Frequently Asked Questions, 3.13.3
2.5.10 Python
Perl Randal Schwartz
Python list.sort() key
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
2.5.11
2.6
2.6.1
class Class
Mailbox .
MboxMailbox MaildirMailbox OutlookMailbox
2.6.2
x x.name(arguments...)
class C:
def meth(self, arg):
return arg * 2 + self.attribute
2.6.3 self
Self meth(self, a, b, c)
x x.meth(a, b, c) meth(x, a, b, c)
self
2.6. 25
Python Frequently Asked Questions, 3.13.3
2.6.4
isinstance(obj, cls)
isinstance(obj, (class1, class2, ...))
Python isinstance(obj, str) isinstance(obj, (int, float, complex))
class P:
pass
class C(P):
pass
Mapping.register(P)
>>> c = C()
>>> isinstance(c, C) #
True
>>> isinstance(c, P) #
True
>>> isinstance(c, Mapping) #
True
#
>>> type(c).__mro__
(<class 'C'>, <class 'P'>, <class 'object'>)
#
>>> Mapping in type(c).__mro__
False
isinstance()
def search(obj):
if isinstance(obj, Mailbox):
... #
elif isinstance(obj, Document):
... #
elif ...
search()
class Mailbox:
def search(self):
... #
class Document:
def search(self):
... #
obj.search()
26 Chapter 2.
Python Frequently Asked Questions, 3.13.3
2.6.5
x
x
Python
class UpperOut:
__setattr__() __setattr__() :
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...
self.__dict__
2.6.6
super()
class Derived(Base):
def meth(self):
super().meth() # Base.meth
2.6.7
class Base:
...
BaseAlias = Base
( )
2.6. 27
Python Frequently Asked Questions, 3.13.3
( )
class Derived(BaseAlias):
...
2.6.8
Python C++ Java
class C:
count = 0 # C.__init__
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # self.count
C self.count = 42 self
”count”
:
C.count = 314
Python
class C:
@staticmethod
def static(arg1, arg2, arg3):
# 'self'
...
def getcount():
return C.count
2.6.9 Python
C++
class C {
C() { cout << "No arguments\n"; }
C(int i) { cout << "Argument is " << i << "\n"; }
}
Python
class C:
def __init__(self, i=None):
if i is None:
print("No arguments")
( )
28 Chapter 2.
Python Frequently Asked Questions, 3.13.3
( )
else:
print("Argument is", i)
class A:
def __one(self):
return 1
def two(self):
return 2 * self.__one()
class B(A):
def three(self):
return 3 * self._A__one()
four = 4 * A()._A__one()
Python
2.6.11 __del__
Python
__del__()
__del__()
gc.collect()
close()
close() __del__() -- __del__()
close() close()
weakref
__del__() sys.stderr
2.6. 29
Python Frequently Asked Questions, 3.13.3
2.6.12
Python
2.6.13 id()
id() CPython
>>> id(1000)
13901272
>>> id(2000)
13901272
id id()
id
2.6.14 is
is a is b id(a) == id(b)
a is a True
True False
3
2) s[0] = x
s[0] is x
3) If an object is a singleton, it means that only one instance of that object can exist. After the assignments a =
None and b = None, it is guaranteed that a is b because None is a singleton.
int str
>>> a = 1000
>>> b = 500
>>> c = b + 500
>>> a is c
False
>>> a = 'Python'
>>> b = 'Py'
>>> c = b + 'thon'
>>> a is c
False
30 Chapter 2.
Python Frequently Asked Questions, 3.13.3
>>> a = []
>>> b = []
>>> a is b
False
1) PEP 8 None
2) None
dict.pop()
_sentinel = object()
3) float('NaN')
collections.abc.Sequence.__contains__() :
def __contains__(self, value):
for v in self:
if v is value or v == value:
return True
return False
2.6.15
__new__() __init__()
:
from datetime import date
class FirstOfMonthDate(date):
"Always choose the first day of the month"
def __new__(cls, year, month, day):
return super().__new__(cls, year, month, 1)
class NamedInt(int):
"Allow text names for some numbers"
xlat = {'zero': 0, 'one': 1, 'ten': 10}
def __new__(cls, value):
value = cls.xlat.get(value, value)
return super().__new__(cls, value)
class TitleStr(str):
"Convert str to name suitable for a URL path"
def __new__(cls, s):
s = s.lower().replace(' ', '-')
s = ''.join([c for c in s if c.isalnum() or c == '-'])
return super().__new__(cls, s)
2.6. 31
Python Frequently Asked Questions, 3.13.3
2.6.16
functools.cached_property() functools.lru_cache()
cached_property
lru_cache hashable
maxsize
class Weather:
"Lookup weather information on a government website"
def current_temperature(self):
"Latest hourly observation"
# Do not cache this because old results
# can be out of date.
@cached_property
def location(self):
"Return the longitude/latitude coordinates of the station"
# Result only depends on the station_id
@lru_cache(maxsize=20)
def historic_rainfall(self, date, units='mm'):
"Rainfall on a given date"
# station_id date unit
station_id cached_property
class Weather:
"Example with a mutable station identifier"
( )
32 Chapter 2.
Python Frequently Asked Questions, 3.13.3
( )
def change_station(self, station_id):
self.station_id = station_id
def __hash__(self):
return hash(self.station_id)
@lru_cache(maxsize=20)
def historic_rainfall(self, date, units='cm'):
'Rainfall on a given date'
# station_id date unit
2.7
2.7.1 .pyc
.py
__pycache__ .pyc .pyc
.py .pyc python PEP
3147
.pyc
__pycache__
Web
PYTHONDONTWRITEBYTECODE Python __pycache__
.pyc
Python .pyc
foo.py xyz.py foo shell python
foo.py xyz .pyc xyz foo .pyc
foo.py
foo .pyc .pyc py_compile
compileall
py_compile compile() :
compileall
compileall.py Python
python -m compileall .
2.7.2
__name__ '__main__'
__name__
def main():
print('Running test...')
( )
2.7. 33
Python Frequently Asked Questions, 3.13.3
( )
...
if __name__ == '__main__':
main()
2.7.3
foo.py:
bar.py:
• foo
• foo
• foo
• foo bar
• bar
• bar
Jim Roskind
•
• import
•
Van Rossum import
Matthias Urlichs
z = importlib.import_module('x.y.z')
34 Chapter 2.
Python Frequently Asked Questions, 3.13.3
2.7.5
Python
import importlib
import modname
importlib.reload(modname)
id
>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'
2.7. 35
Python Frequently Asked Questions, 3.13.3
36 Chapter 2.
CHAPTER 3
3.1 Python
Guido van Rossum Python
/ C
:
if (x <= y)
x++;
y--;
z++;
x++ C
x > y y
/ Python C
/
20--30 20 Python
20 C / --
--
3.2
3.3
:
37
Python Frequently Asked Questions, 3.13.3
>>> x = 1.2
x 1.2 ( )
1.0011001100110011001100110011001100110011001100110011 ( )
1.1999999999999999555910790149937383830547332763671875 ( )
53 Python 15-16
Python
3.4 Python
Python 8
Python ”8”
3.5 self
Modula-3
self.x self.meth()
C++
Python
C++ Java m_
C++
:: -- Python baseclass.
methodname(self, <argument list>) __init__()
Python
C++
Python self.var
self.var
Python
38 Chapter 3.
Python Frequently Asked Questions, 3.13.3
3.6
Python 3.8
:= :
PEP 572
3.8 join()
Python 1.6
String
"1, 2, 4, 8, 16"
(String Constant)
split()
:
join()
3.6. 39
Python Frequently Asked Questions, 3.13.3
3.9
try/except 2.0
Python :
try:
value = mydict[key]
except KeyError:
mydict[key] = getvalue(key)
value = mydict[key]
dict key
if key in mydict:
value = mydict[key]
else:
value = mydict[key] = getvalue(key)
case
func = functions[value]
func()
getattr()
class MyVisitor:
def visit_a(self):
...
visit_
C switch-case-default
3.11
1 Python C Python
C
2 Stackless Python C
40 Chapter 3.
Python Frequently Asked Questions, 3.13.3
3.12 lambda
Python lambda Python
Python lambda Python
lambda
Python lambda
-- lambda
3.13 Python C
Cython Python C Nuitka Python C++
Python
3.14 Python
Python Python CPython
gc
Python CPython :
CPython f
GC
python with
3.15 CPython
C ( Boehm GC
; Python
)
Python GC Python GC
malloc() free() Python malloc()
free() Python CPython malloc() free()
3.16 CPython
Python Python
C Purify
Python
Python atexit
3.12. lambda 41
Python Frequently Asked Questions, 3.13.3
3.17
Pascal
records C structs
os.listdir('.')
key key
3.18 CPython
CPython lisp
a[i]
3.19 CPython
CPython B-
hash()
'Python' -539294296 'python'
1142331976
-- O O(1) --
3.20 key
tuple(L)
L
• ID
:
KeyError [1, 2] id id
== is
•
d.keys()
42 Chapter 3.
Python Frequently Asked Questions, 3.13.3
__eq__() __hash__()
class ListWrapper:
def __init__(self, the_list):
self.the_list = the_list
def __hash__(self):
l = self.the_list
result = 98767 - len(l)*555
for i, el in enumerate(l):
try:
result = result + (hash(el) % 9999999) * 1001 + i
except Exception:
result = (result % 7777777) + i * 333
return result
3.21 list.sort()
list.sort()
sorted()
keys :
3.22 Python
C++ Java
Python
Python
3.21. list.sort() 43
Python Frequently Asked Questions, 3.13.3
Python
list.append()
list.append()
Python
3.23 goto
1970 goto
Python if or, and if/else
while for continue break
goto C,
Fortran go goto :
try:
...
if condition: raise label() # label
...
except label: #
pass
...
goto
3.24 r-strings
( )
r-string
Windows Windows :
f = open("/mydir/file.txt") #
DOS
with obj:
a = 1 # to obj.a = 1
total = total + 1 # obj.total = obj.total + 1
44 Chapter 3.
Python Frequently Asked Questions, 3.13.3
Python
ObjectPascal Delphi C++
--
Python
def foo(a):
with a:
print(x)
a x Python
a x with
Python
with Python
:
function(args).mydict[index][index].a = 21
function(args).mydict[index][index].b = 42
function(args).mydict[index][index].c = 63
ref = function(args).mydict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63
Python
( https://mail.python.org/pipermail/python-ideas/2016-May/040070.html)
3.26 with
with contextlib.
closing(generator)
3.27 if/while/def/class
(ABC ) :
if a == b
print(a)
if a == b:
print(a)
FAQ
3.26. with 45
Python Frequently Asked Questions, 3.13.3
3.28 Python
Python :
[1, 2, 3,]
('a', 'b', 'c',)
d = {
"A":[1, 5],
"B":[6, 7], #
}
x = [
"fee",
"fie"
"foo",
"fum"
]
46 Chapter 3.
CHAPTER 4
FAQ
4.1
4.1.1 X
import sys
print(sys.builtin_module_names)
#!/usr/local/bin/python
Python
Python env Python
PATH Unix
47
Python Frequently Asked Questions, 3.13.3
#!/usr/bin/env python
/usr/bin/env env
hack Alex Rezinsky
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
__doc__
__doc__ = """...Whatever..."""
4.1.6
handler(signum, frame)
4.2
4.2.1 Python
Python doctest docstring docstring
if __name__ == "__main__":
main_logic()
48 Chapter 4. FAQ
Python Frequently Asked Questions, 3.13.3
Python
if __name__ == "__main__":
self_test()
Python
4.2.2 docstring
pydoc Python HTML API
epydoc Sphinx
4.2.3
Unix curses curses
4.3
4.3.1
threading _thread threading _thread
4.3.2
sleep
import threading, time
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10) # <---------------------------!
sleep
def thread_task(name, n):
time.sleep(0.001) # <--------------------!
for i in range(n):
print(name, i)
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
( )
4.3. 49
Python Frequently Asked Questions, 3.13.3
( )
T.start()
time.sleep(10)
time.sleep() queue
queue append queue queue
4.3.3
concurrent.futures ThreadPoolExecutor
queue
Queue .put(obj) .get()
#
#
#
def worker():
print('Running worker')
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except queue.Empty:
print('Worker', threading.current_thread(), end=' ')
print('queue empty')
break
else:
print('Worker', threading.current_thread(), end=' ')
print('running with argument', arg)
time.sleep(0.5)
#
q = queue.Queue()
# 5
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
#
for i in range(50):
q.put(i)
#
print('Main thread sleeping')
time.sleep(5)
Running worker
Running worker
Running worker
Running worker
Running worker
( )
50 Chapter 4. FAQ
Python Frequently Asked Questions, 3.13.3
( )
Main thread sleeping
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
...
Queue
4.3.4
Python VM global interpreter lock GIL Python
sys.setswitchinterval() Python
C
PVM int list dict
L L1 L2 D D1 D2 x y i j int
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
__del__()
4.3.5
global interpreter lock GIL Python
Python GIL Python CPU
PEP 703 Python CPython GIL
GIL GIL GIL
Python 3.13
4.3. 51
Python Frequently Asked Questions, 3.13.3
ProcessPoolExecutor
multiprocessing API
C C C
GIL zlib hashlib
GIL GIL
Python 3.12 C API Python 3.13 Python
3
4.4
4.4.1
os.remove(filename) os.unlink(filename) os
unlink() Unix
os.rmdir() os.mkdir() os.makedirs(path) path
os.removedirs(path)
shutil.rmtree()
os.rename(old_path, new_path)
f = open(filename, "rb+") f.truncate(offset)
offset os.open() os.ftruncate(fd, offset)
fd
shutil copyfile() copytree() rmtree()
4.4.2
shutil copyfile() Windows NTFS
macOS HFS+
shutil.copy2()
4.4.3
struct
Python
2 4
import struct
> h 2
l 4
array
open() "rb"
"r" f.read() str bytes
52 Chapter 4. FAQ
Python Frequently Asked Questions, 3.13.3
4.4.5 RS232
Win32, OSX, Linux, BSD, Jython, IronPython:
pyserial
Unix Mitch Chapman
https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())
0 1 2
4.5 / Internet
4.5.1 Python WWW
internet netdata Python
web
Paul Boddie https://wiki.python.org/moin/WebProgramming
4.5.2 HTML
Web wiki
4.5.3 Python
smtplib
SMTP
4.5. / Internet 53
Python Frequently Asked Questions, 3.13.3
( )
if not line:
break
msg += line
#
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
import os
connect_ex() errno
connect_ex() -- 0 errno.EISCONN -- socket select.select()
asyncio Twisted
4.6
4.6.1 Python
wiki
54 Chapter 4. FAQ
Python Frequently Asked Questions, 3.13.3
4.6.2 Python
pickle
shelve pickle (g)dbm Python
4.7
4.7.1 Python
random
import random
random.random()
[0, 1)
• randrange(a, b) [a, b)
• uniform(a, b) [a, b)
• normalvariate(mean, sdev)
• choice(S)
• shuffle(L)
Random
4.7. 55
Python Frequently Asked Questions, 3.13.3
56 Chapter 4. FAQ
CHAPTER 5
5.1 C
C extending-index
Python
5.2 C++
C++ C Python include extern "C" { ... }
Python extern "C" C++
5.3 C
C
Cython Pyrex Python C Cython Pyrex
Python C API
Python C C++ SWIG
SIP, CXX Boost Weave C++
5.4 C Python
PyRun_SimpleString() __main__
0 ( SyntaxError) -1
PyRun_String() Python/pythonrun.c PyRun_SimpleString()
5.5 C Python
PyRun_String() Py_eval_input
57
Python Frequently Asked Questions, 3.13.3
5.6 Python C
PyTuple_Size() PyTuple_GetItem()
PyList_Size() PyList_GetItem()
PyBytes_Size() PyBytes_AsStringAndSize()
Python C strlen()
5.7 Py_BuildValue()
PyTuple_Pack()
5.8 C
PyObject_CallMethod()
Py_BuildValue() :
PyObject *
PyObject_CallMethod(PyObject *object, const char *method_name,
const char *arg_format, ...);
Py_DECREF()
PyObject_CallObject()
”()” ”(i)”
io.StringIO
58 Chapter 5. /
Python Frequently Asked Questions, 3.13.3
( )
>>> sys.stderr.write(sys.stdout.getvalue())
foo
hello world!
5.10 C Python
:
module = PyImport_ImportModule("<modulename>");
sys.modules
sys.modules["<modulename>"]
sys.modules
PyObject_SetAttrString()
5.11 Python C ++
” ”
Python C C++ C
Python C++
C ++ C
5.13
GDB
.gdbinit
5.10. C Python 59
Python Frequently Asked Questions, 3.13.3
br _PyImport_LoadDynamicModule
GDB
$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue #
gdb) finish #
gdb) br myfunction.c:50
gdb) continue
5.15
Python ( if
)
Python codeop IDLE
C PyRun_InteractiveLoop() Python
PyOS_ReadlineFunctionPointer()
Modules/readline.c Parser/myreadline.c
5.17 C
Python
int list dict
60 Chapter 5. /
CHAPTER 6
Python Windows
” ” Windows
cmd
Windows ” ”
C:\>
D:\YourName\Projects\Python>
Python
Python Python
Python
py
py
C:\Users\YourName> py
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python
Python
>>> print("Hello")
Hello
>>> "Hello" * 3
'HelloHelloHello'
61
Python Frequently Asked Questions, 3.13.3
Python exit()
Ctrl Z Enter Windows
‣ ‣ Python 3.x ‣ Python ( )
>>> exit() Ctrl-Z
Windows python
py Python Python
Python hello.py
:
C:\Users\YourName>
py py :
C:\Users\YourName> py Desktop\hello.py
hello
6.2 Python
Windows Python .py (Python.File)
(D:\Program Files\Python\python.exe "%1" %*)
foo.py foo
.py PATHEXT
6.3 Python
Python Windows Python
Windows Python
McAfee
6.4 Python
Python
Windows
LoadLibraryEx() pythonNN.dll Windows GetProcAddress()
pythonNN.dll Python C API
Python C API C
2. SWIG Python ”
” SWIG .exe C (!)
DLL
3. SWIG init C
leo init initleo() SWIG init initleoc()
2 C .exe Python
4. Python
#include <Python.h>
...
Py_Initialize(); // Python
initmyAppc(); //
PyRun_SimpleString("import myApp"); //
1: FILE * ” ”
struct FILE
2 void SWIG
Py_INCREF(Py_None);
_resultobj = Py_None;
return _resultobj;
return Py_BuildValue("");
MSVC
Tools ‣ Options ‣ Tabs Default Tab size Indent size 4
6.8
msvcrt Windows kbhit()
getch()
6.9 api-ms-win-crt-runtime-l1-1-0.dll
Windows 8.1 Python 3.5
Microsoft support page
C
GUI
7.1
7.2 Python GUI
Python Tcl/Tk tkinter
Python Tk
Tcl/Tk Tcl/Tk macOS Windows Unix
Python Wiki GUI
7.3 Tkinter
7.3.1 Tkinter
Freeze Tkinter
Tcl Tk
Tcl Tk TCL_LIBRARY TK_LIBRARY
7.3.2 I/O Tk
Windows I/O Tk Xt
XtAddInput() I/O
Tk tkinter-file-handlers
7.3.3 Tkinter
bind()
Tk focus
takefocus
65
Python Frequently Asked Questions, 3.13.3
66 Chapter 7. GUI
CHAPTER 8
Python
8.1 Python
Python
Google NASA
Python Beginner’s Guide to Python.
8.2 Python
Python
•
Python
• Python Python
GUI
• Windows Python Hewlett-Packard Compaq
Python HP/Compaq Python
• Unix macOS Linux Python
8.3 Python
Python
Python Windows
/
Python
Python
Python Python
Python
67
Python Frequently Asked Questions, 3.13.3
68 Chapter 8. Python
APPENDIX A
>>>
interactive shell Python
...
• Ellipsis
abstract base class --
ABC duck-typing
hasattr() ABC
isinstance() issubclass() abc
Python ABC collections.abc numbers
io importlib.abc abc
ABC
annotation --
__annotations__
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• : /
* iterable 3 5 :
69
Python Frequently Asked Questions, 3.13.3
complex(3, 5)
complex(*(3, 5))
calls
yield try
__anext__()
PEP 492 PEP 525
asynchronous iterable --
async for __aiter__() asynchronous
iterator PEP 492
asynchronous iterator --
__aiter__() __anext__() __anext__() awaitable
async for __anext__()
StopAsyncIteration PEP 492
attribute --
o a
o.a
identifiers
setattr() getattr()
awaitable --
await coroutine __await__()
PEP 492
BDFL
Guido van Rossum Python
binary file --
file object ('rb', 'wb' 'rb+')
sys.stdin.buffer sys.stdout.buffer io.BytesIO gzip.GzipFile
borrowed reference --
Python C API
strong reference
70 Appendix A.
Python Frequently Asked Questions, 3.13.3
bytecode --
Python CPython Python
.pyc
” ” virtual machine Python
Python
dis
callable --
( argument) :
callback --
class --
class variable --
( )
closure variable --
nested scope free variable
nonlocal
inner x print x :
def outer():
x = 0
def inner():
nonlocal x
x += 1
print(x)
return inner
codeobject.co_freevars
free variable
complex number --
-1
i j Python
j 3+1j math
cmath
71
Python Frequently Asked Questions, 3.13.3
context --
contiguous --
C Fortran C Fortran
C-
Fortran
coroutine --
decorator --
@wrapper
classmethod() staticmethod()
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
descriptor --
__get__(), __set__() __delete__()
a.b
a b b
Python
72 Appendix A.
Python Frequently Asked Questions, 3.13.3
descriptors
dictionary --
__hash__() __eq__()
Perl hash
dictionary comprehension --
results = {n: n **
2 for n in range(10)} n n ** 2 comprehensions
dictionary view --
dict.keys(), dict.values() dict.items()
list(dictview) dict-views
docstring --
__doc__
duck-typing --
type() isinstance()
( ) hasattr() EAFP
EAFP
Python
try except
LBYL C
expression --
statement while
extension module --
C C++ Python C API
f-string -- f-
'f' 'F' f-
PEP 498
file object --
API read() write()
/
: ,
io open()
file-like object --
file object
filesystem encoding and error handler --
Python Unicode
128
API UnicodeError
sys.getfilesystemencoding() sys.getfilesystemencodeerrors()
73
Python Frequently Asked Questions, 3.13.3
locale encoding
finder --
loader
: sys.meta_path
sys.path_hooks
finders-and-loaders importlib
floor division --
// 11 // 4
2 2.75 (-11) // 4 -3
-2.75 PEP 238
free threading --
Python global
interpreter lock Python PEP 703
free variable --
function
variable annotation PEP 484 annotations-howto
__future__
future , from __future__ import <feature> Python
__future__ feature
garbage collection --
Python
gc
generator --
generator iterator yield
for- next()
generator iterator --
generator
74 Appendix A.
Python Frequently Asked Questions, 3.13.3
yield try
generator expression --
iterator expression for
if :
generic function --
GIL
global interpreter lock
global interpreter lock --
CPython Python bytecode
dict CPython
Python
frozenset
id()
IDLE
Python idle Python
immortal --
PEP 683 CPython
reference count
True None CPython
immutable --
75
Python Frequently Asked Questions, 3.13.3
import path --
path based finder
sys.path __path__
importing --
Python Python
importer --
finder loader
interactive --
Python
python
help(x)
tut-interac
interpreted --
Python
/ interactive
interpreter shutdown --
Python
__main__
iterable --
list, str tuple
dict, __iter__() sequence
__getitem__()
typeiter
CPython __iter__() CPython
key function --
locale.strxfrm()
Python min(),
max(), sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.nlargest()
itertools.groupby()
str.lower()
lambda lambda r: (r[0], r[2]) operator.
76 Appendix A.
Python Frequently Asked Questions, 3.13.3
keyword argument --
argument
lambda
expression lambda
lambda [parameters]: expression
LBYL
EAFP if
LBYL
if key in mapping: return mapping[key] mapping
key EAFP
lexical analyzer --
token
list --
Python sequence
O(1)
list comprehension --
result = ['{:#04x}'.
format(x) for x in range(256) if x % 2 == 0] 0 255
0x.. if range(256)
loader --
exec_module() create_module() Loader
finder
• finders-and-loaders
• importlib.abc.Loader
• PEP 302
locale encoding --
Unix LC_CTYPE locale.setlocale(locale.
LC_CTYPE, new_locale)
locale.getencoding()
Python
77
Python Frequently Asked Questions, 3.13.3
metaclasses
method --
module-specs
MRO
method resolution order
mutable --
id() immutable
named tuple --
time.localtime() os.stat()
sys.float_info:
>>> sys.float_info[1] #
1024
>>> sys.float_info.max_exp #
1024
>>> isinstance(sys.float_info, tuple) #
True
tuple
typing.
NamedTuple collections.namedtuple()
namespace --
builtins.open os.open()
namespace package --
package regular
package __init__.py
regular package
PEP 420 reference-namespace-package
module
78 Appendix A.
Python Frequently Asked Questions, 3.13.3
nested scope --
nonlocal
new-style class --
Python
Python __slots__ __getattribute__()
object --
object new-style class
optimized scope --
package --
Python module __path__
Python
regular package namespace package
parameter --
function argument
• positional-or-keyword
foo bar:
• positional-only
/ posonly1 posonly2:
• keyword-only
*
kw_only1 kw_only2:
• var-positional
* args:
• var-keyword
** kwargs
79
Python Frequently Asked Questions, 3.13.3
importlib.abc.PathEntryFinder
path entry hook --
path entry sys.path_hooks
path entry finder
path based finder --
import path
path-like object --
str bytes
os.PathLike os.PathLike os.
fspath() str bytes os.fsdecode() os.fsencode()
str bytes PEP 519
PEP
Python PEP Python
Python PEP
PEP Python
PEP
PEP 1
portion --
zip PEP
420
positional argument --
argument
provisional API -- API
API
-- API
API
PEP
411
provisional package --
provisional API
Python 3000
Python 3.x 3
Py3k
Pythonic
Python
Python for
Python :
for i in range(len(food)):
print(food[i])
Pythonic :
80 Appendix A.
Python Frequently Asked Questions, 3.13.3
qualified name --
PEP 3155 :
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
email.mime.text:
reference count --
immortal
Python
CPython sys.getrefcount()
regular package --
package __init__.py
namespace package
REPL
- - read-eval-print loop interactive shell
__slots__
sequence --
iterable __getitem__()
__len__() list, str, tuple bytes
dict __getitem__() __len__()
hashable
collections.abc.Sequence __getitem__()
__len__() count(), index(), __contains__() __reversed__()
register()
set comprehension --
results = {c for c
in 'abracadabra' if c not in 'abc'} {'r', 'd'} comprehensions
single dispatch --
generic function
slice --
sequence []
variable_name[1:3:5] slice
81
Python Frequently Asked Questions, 3.13.3
soft deprecated --
API API
API
PEP 387: Soft Deprecation
special method --
Python
specialnames
statement --
expression
if while for
static type checker --
Python
typing
strong reference --
Python C API
Py_INCREF() Py_DECREF()
Py_NewRef()
Py_DECREF()
borrowed reference
text encoding --
Python Unicode U+0000--U+10FFFF
” ”
text file --
str file object
text encoding 'r' 'w' sys.stdin
sys.stdout io.StringIO
binary file
( )
triple-quoted string --
” ’
type --
Python
__class__ type(obj)
type alias --
:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
82 Appendix A.
Python Frequently Asked Questions, 3.13.3
class C:
field: 'annotation'
int :
count: int = 0
annassign
function annotation, PEP 484 PEP 526 annotations-howto
virtual environment --
Python Python
Python
venv
virtual machine --
Python bytecode
Zen of Python -- Python
Python
”import this”
83
Python Frequently Asked Questions, 3.13.3
84 Appendix A.
APPENDIX B
Python
reporting-bugs
B.1 Python
Python Python Python Python Misc/ACKS
Python Python
85
Python Frequently Asked Questions, 3.13.3
86 Appendix B.
APPENDIX C
C.1
Python 1990 Guido van Rossum Stichting Mathematisch Centrum (CWI https:
//www.cwi.nl) ABC Guido Python
1995 Guido Reston Corporation for National Research Initiatives (CNRI https:
//www.cnri.reston.va.us) Python
2000 5 Guido Python BeOpen.com BeOpen PythonLabs
10 PythonLabs Digital Creations Zope Corporation 2001 Python Software
Foundation (PSF https://www.python.org/psf/) Python
Zope Corporation PSF
Python ( https://opensource.org)
Python GPL
GPL ? (1)
0.9.0 1.2 n/a 1991-1995 CWI
1.3 1.5.2 1.2 1995-1999 CNRI
1.6 1.5.2 2000 CNRI
2.0 1.6 2000 BeOpen.com
1.6.1 1.6 2001 CNRI (2)
2.1 2.0+1.6.1 2001 PSF
2.0.1 2.0+1.6.1 2001 PSF
2.1.1 2.1+2.0.1 2001 PSF
2.1.2 2.1.1 2002 PSF
2.1.3 2.1.2 2002 PSF
2.2 2.1.1 2001 PSF
87
Python Frequently Asked Questions, 3.13.3
GPL
(2) Richard Stallman 1.6.1 GPL
CNRI Stallman CNRI 1.6.1 GPL ” ”
Guido
C.2 Python
Python Python Software Foundation License Version 2
Python 3.8.6 PSF License Version 2 Zero-Clause BSD
license
Python
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i.e., "Copyright © 2001-2024 Python Software Foundation; All Rights
Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
88 Appendix C.
Python Frequently Asked Questions, 3.13.3
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
is made available subject to the terms and conditions in CNRI's License
Agreement. This Agreement together with Python 1.6.1 may be located on the
( )
C.2. Python 89
Python Frequently Asked Questions, 3.13.3
( )
internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the
internet using the following URL: http://hdl.handle.net/1895.22/1013".
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.
90 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
C.3
Python
C.3. 91
Python Frequently Asked Questions, 3.13.3
( )
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C.3.2
socket getaddrinfo() getnameinfo() WIDE : https://www.wide.ad.jp/
Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.3
test.support.asynchat test.support.asyncore :
Copyright 1996 by Sam Rushing
92 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
C.3.4 Cookie
http.cookies :
C.3.5
trace :
Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
( )
C.3. 93
Python Frequently Asked Questions, 3.13.3
( )
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
C.3.7 XML
xmlrpc.client :
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
( )
94 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
test.test_epoll :
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3. 95
Python Frequently Asked Questions, 3.13.3
C.3.10 SipHash24
Python/pyhash.c Marek Majkowski’ Dan Bernstein SipHash24
:
<MIT License>
Copyright (c) 2013 Marek Majkowski <marek@popcount.org>
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>
Original location:
https://github.com/majek/csiphash/
C.3.12 OpenSSL
hashlib, posix ssl OpenSSL Python Windows
macOS OpenSSL OpenSSL
OpenSSL 3.0 Apache License v2:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
( )
96 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
C.3. 97
Python Frequently Asked Questions, 3.13.3
( )
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
( )
98 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
C.3.13 expat
pyexpat expat --with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
C.3. 99
Python Frequently Asked Questions, 3.13.3
( )
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.14 libffi
ctypes _ctypes C libffi
--with-system-libffi:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
zlib zlib zlib :
Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler
1. The origin of this software must not be misrepresented; you must not
( )
100 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
C.3.16 cfuhash
tracemalloc cfuhash :
Copyright (c) 2005 Don Owens
All rights reserved.
C.3.17 libmpdec
decimal _decimal C libmpdec
--with-system-libmpdec:
C.3. 101
Python Frequently Asked Questions, 3.13.3
( )
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.19 mimalloc
MIT :
Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
102 Appendix C.
Python Frequently Asked Questions, 3.13.3
( )
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
C.3.20 asyncio
asyncio uvloop 0.16 MIT :
Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
( )
C.3. 103
Python Frequently Asked Questions, 3.13.3
( )
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104 Appendix C.
APPENDIX D
Python
© 2001-2024 Python
© 2000 BeOpen.com
© 1995-2000 Corporation for National Research Initiatives
© 1991-1995 Stichting Mathematisch Centrum
105
Python Frequently Asked Questions, 3.13.3
106 Appendix D.
class variable -- , 71
..., 69 closure variable -- , 71
>>>, 69 complex number -- , 71
__future__, 74 context -- , 72
__slots__, 81 context manager -- , 72
, 72 context variable -- , 72
contiguous -- , 72
method -- , 82 coroutine -- , 72
coroutine function -- , 72
PATH, 47, 48 CPython, 72
PYTHON_GIL, 75 current context -- , 72
PYTHONDONTWRITEBYTECODE, 33
D
method -- , 77 decorator -- , 72
descriptor -- , 72
A dictionary -- , 73
abstract base class -- , 69 dictionary comprehension -- , 73
annotation -- , 69 dictionary view -- , 73
argument -- docstring -- , 73
, 12 duck-typing -- , 73
argument -- , 69
asynchronous context manager --
E
, 70 EAFP, 73
asynchronous generator -- , 70 expression -- , 73
asynchronous generator iterator -- extension module -- , 73
, 70
asynchronous iterable -- , 70 F
asynchronous iterator -- , 70 f-string -- f- , 73
attribute -- , 70 file object -- , 73
awaitable -- , 70 file-like object -- , 73
filesystem encoding and error handler --
B , 73
BDFL, 70 finder -- , 74
binary file -- , 70 floor division -- , 74
borrowed reference -- , 70 Fortran , 72
bytecode -- , 71 free threading -- , 74
bytes-like object -- , 71 free variable -- , 74
function -- , 74
C function annotation -- , 74
C , 72
callable -- , 71 G
callback -- , 71 garbage collection -- , 74
class -- , 71 generator -- , 74
107
Python Frequently Asked Questions, 3.13.3
108
Python Frequently Asked Questions, 3.13.3
Q
qualified name -- , 81
R
reference count -- , 81
regular package -- , 81
REPL, 81
S
sequence -- , 81
set comprehension -- , 81
single dispatch -- , 81
slice -- , 81
soft deprecated -- , 82
special method -- , 82
statement -- , 82
static type checker -- , 82
strong reference -- , 82
T
text encoding -- , 82
text file -- , 82
triple-quoted string -- , 82
type -- , 82
type alias -- , 82
type hint -- , 83
U
universal newlines -- , 83
V
variable annotation -- , 83
virtual environment -- , 83
virtual machine -- , 83
, 82
Z
Zen of Python -- Python , 83
109