KEMBAR78
Python Frequently Asked Questions: Guido Van Rossum and The Python Development Team | PDF | Python (Programming Language) | System Software
0% found this document useful (0 votes)
43 views117 pages

Python Frequently Asked Questions: Guido Van Rossum and The Python Development Team

The document is a FAQ for Python, authored by Guido van Rossum and the Python development team, dated January 27, 2025. It contains a comprehensive index of topics related to Python programming, including error handling, syntax, and various features of the language. The document serves as a resource for users seeking answers to common questions about Python.

Uploaded by

chiao.brett
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views117 pages

Python Frequently Asked Questions: Guido Van Rossum and The Python Development Team

The document is a FAQ for Python, authored by Guido van Rossum and the Python development team, dated January 27, 2025. It contains a comprehensive index of topics related to Python programming, including error handling, syntax, and various features of the language. The document serves as a resource for users seeking answers to common questions about Python.

Uploaded by

chiao.brett
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Python Frequently Asked Questions

3.13.3

Guido van Rossum and the Python development team

27, 2025

Python Software Foundation


Email: docs@python.org
Contents

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

Modula-2+ Modula-3 Modula-3


Modula-3 Python
CWI Amoeba C
Bash Amoeba
Bash Amoeba

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 --

alpha, beta release candidate alpha


alpha beta
release candidate
Alpha, beta :
• N alpha ”aN”
• N beta ”bN”
• N ”rcN”
2.0aN 2.0bN 2.0rcN
2.0

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

Git Python Python

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.1.17 ”Monty Python ”


:)

1.2 Python
1.2.1 Python
1991 6 18
3.9 Python 12 (PEP 602)

3.5.3, 3.6.2

Python Python 3.x


Python 2.x

1.2.2 Python

Python
Linux
comp.lang.python Python

1.2.3 Python
https://www.python.org/about/success Python Python

Python Mailman Zope Linux


Red Hat Python Python
Google, Yahoo Lucasfilm

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

Pascal, C C++ Java


Python Python
Python
Python

Python Java 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]

Python IDE IDLE Python Tkinter Python IDE Emacs


Emacs Python
Python wiki Python

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)

PythonWin Python IDE pdb GUI PythonWin


PythonWin PythonWin pywin32
ActivePython
Eric PyQt Scintilla IDE
trepan3k gdb
Visual Studio Code IDE
Python IDE
• Wing IDE
• Komodo IDE
• PyCharm

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

freeze Tools/freeze Python Python


C 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

>>> def foo():


... x = 10
... def bar():
... nonlocal x
... print(x)
... x += 1
... bar()
... print(x)
...
>>> foo()
10
11

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)

n=x lambda n lambda x


n 1 lambda 0 2 lambda 1 3 2
lambda
>>> squares[2]()
4
>>> squares[4]()
16

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

2. Python site-packages dateutil requests PIL.


Image

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

mydict mydict foo()


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
* **
* **

def f(x, *args, **kwargs):


...
kwargs['width'] = '14.3c'
...
g(x, *args, **kwargs)

2.2.8

def func(foo, bar=None, **kwargs):


pass

foo bar kwargs func func

func(42, bar=314, extra=somevar)

42 314 somevar

2.2.9 ’y’ ’x’

>>> 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

+= a_list += [1, 2, 3] a_list.extend([1, 2, 3])


a_list some_tuple += (1, 2, 3) some_int += 1

• list dict set

• str int tuple

is id()

2.2.10
Python

1)

>>> def func1(a, b):


... a = 'new-value' # a b
... b = b + 1 #
... return a, b #
...
>>> x, y = 'old-value', 99
>>> func1(x, y)
('new-value', 100)

2)
3)

>>> def func2(a):


... a[0] = 'new-value' # 'a'
... a[1] = a[1] + 1 #
...
>>> args = ['old-value', 99]
>>> func2(args)
>>> args
['new-value', 100]

4) :

>>> def func3(args):


... args['a'] = 'new-value' # args
... args['b'] = args['b'] + 1 #
...
>>> args = {'a': 'old-value', 'b': 99}
>>> func3(args)
>>> args
{'a': 'new-value', 'b': 100}

2.2. 13
Python Frequently Asked Questions, 3.13.3

5)

>>> class Namespace:


... def __init__(self, /, **args):
... for key, value in args.items():
... setattr(self, key, value)
...
>>> def func4(args):
... args.a = 'new-value' # args Namespace
... args.b = args.b + 1 #
...
>>> args = Namespace(a='old-value', b=99)
>>> func4(args)
>>> vars(args)
{'a': 'new-value', 'b': 100}

2.2.11 Python
linear(a,b) a*x+b
f(x)

def linear(a, b):


def result(x):
return a * x + b
return result

class linear:

def __init__(self, a, b):


self.a, self.b = a, b

def __call__(self, x):


return self.a * x + self.b

taxes = linear(0.3, 2)

taxes(10e6) == 0.3 * 10e6 + 2

class exponential(linear):
# __init__
def __call__(self, x):
return self.a * (x ** self.b)

class counter:

value = 0

def set(self, x):


self.value = x
( )

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

inc() dec() reset()

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

comp.lang.python Fredrik Lundh

2.2. 15
Python Frequently Asked Questions, 3.13.3

2.2.15
Python

>>> "a" in "b", "a"


(False, 'a')

("a" in "b"), "a"

"a" in ("b", "a")

= +=

2.2.16 C ”?:”

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y

Python 2.5

[expression] and [on_true] or [on_false]

on_true ... if
... else ...

2.2.17 Python ?
lambda lambda Ulf Bartelt
:

from functools import reduce

# < 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()

>>> divmod(x=3, y=4)


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: divmod() takes no keyword arguments

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

2.3.3 int SyntaxError


int SyntaxError :

>>> 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

Unicode io.StringIO array

>>> 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!'

>>> import array


>>> a = array.array('w', s)
>>> print(a)
array('w', 'Hello, world')
>>> a[0] = 'y'
( )

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 = {'go': a, 'stop': b} #

dispatch[get_input()]() #

• getattr()

import foo
getattr(foo, 'bar')()

getattr()

class Foo:
def do_foo(self):
...

def do_bar(self):
...

f = getattr(foo_instance, 'do_' + opname)


f()

• locals()

def myFunc():
print("hello")

fname = "myFunc"

f = locals()[fname]
f()

2.3.8 Perl chomp()


S.rstrip("\r\n") S
S

>>> lines = ("line 1 \r\n"


... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '

2.3. 19
Python Frequently Asked Questions, 3.13.3

S.rstrip()

2.3.9 scanf() sscanf()

split()
int() float() split() ”sep”

C sscanf

2.3.10 UnicodeDecodeError UnicodeEncodeError


unicode-howto

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\\'

>>> r'C:\this\will\work' '\\'


'C:\\this\\will\\work\\'

Windows os.path.join() :

>>> os.path.join(r'C:\this\will\work', '')


'C:\\this\\will\\work\\'

>>> r'backslash\'preserved'
"backslash\\'preserved"

2.4
2.4.1

• Python FAQ CPython


• I/O
• profile

• 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([1, 2, 3]) (1, 2, 3) tuple('abc') ('a', 'b', 'c')

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

mylist[:] = filter(keep_function, mylist)


mylist[:] = (x for x in mylist if keep_condition)
mylist[:] = [x for x in mylist if keep_condition]

2.5.6 Python

["this", 1, "is", "an", "array"]

C Pascal Python

array
NumPy

22 Chapter 2.
Python Frequently Asked Questions, 3.13.3

Lisp cons :

lisp_list = ("like", ("this", ("example", None) ) )

Lisp car lisp_list[0] cdr


lisp_list[1] Python

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 :

result = [obj.method() for obj in mylist]

result = [function(obj) for obj in mylist]

for :

for obj in mylist:


obj.method()

for obj in mylist:


function(obj)

2.5. / 23
Python Frequently Asked Questions, 3.13.3

2.5.9 a_tuple[i] += [’item’]


Python

list +=
:

>>> a_tuple = (1, 2)


>>> a_tuple[0] += 1
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

1 1 a_tuple[0] 2
2 0

>>> result = a_tuple[0] + 1


>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

>>> a_tuple = (['foo'], 'bar')


>>> a_tuple[0] += ['item']
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

>>> a_tuple[0]
['foo', 'item']

(a) __iadd__()
+= (b) __iadd__()
extend() += list.extend()
:

>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]

>>> result = a_list.__iadd__([1])


>>> a_list = result

a_list a_list
a_list

24 Chapter 2.
Python Frequently Asked Questions, 3.13.3

>>> result = a_tuple[0].__iadd__(['item'])


>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

__iadd__() result a_tuple[0]

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

>>> list1 = ["what", "I'm", "sorting", "by"]


>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']

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))

isinstance() abstract base class


True MRO:

from collections.abc import Mapping

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:

def __init__(self, outfile):


self._outfile = outfile

def write(self, s):


self._outfile.write(s.upper())

def __getattr__(self, name):


return getattr(self._outfile, name)

UpperOut write() self._outfile.write()


self._outfile
__getattr__()

__setattr__() __setattr__() :
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...

__setattr__() object.__setattr__() self :


class X:
def __setattr__(self, name, value):
# ...
object.__setattr__(self, name, value)

self.__dict__

2.6.6
super()

class Derived(Base):
def meth(self):
super().meth() # Base.meth

super() (self ) type(self).__mro__


method resolution order (MRO) MRO Derived : Base

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

isinstance(c, C) c c.count C.count c c.


__class__ C

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)

def __init__(self, *args):


...

2.6.10 __spam _SomeClassName__spam


__spam
_classname__spam
classname

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__

del __del__() -- __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

>>> a = 1000; b = 2000


>>> id(a)
13901272
>>> id(b)
13891296

2.6.14 is
is a is b id(a) == id(b)
a is a True
True False
3

1) new = old new is


old

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()

def pop(self, key, default=_sentinel):


if key in self:
value = self[key]
del self[key]
return value
if default is _sentinel:
raise KeyError(key)
return default

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

>>> FirstOfMonthDate(2012, 2, 14)


FirstOfMonthDate(2012, 2, 1)
>>> NamedInt('ten')
10
>>> NamedInt(20)
20
>>> TitleStr('Blog: Why Python Rocks')
'blog-why-python-rocks'

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 __init__(self, station_id):


self._station_id = station_id
# The _station_id is private and immutable

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

lru_cache station_id __eq__() __hash__()


:

class Weather:
"Example with a mutable station identifier"

def __init__(self, station_id):


self.station_id = station_id

( )

32 Chapter 2.
Python Frequently Asked Questions, 3.13.3

( )
def change_station(self, station_id):
self.station_id = station_id

def __eq__(self, other):


return self.station_id == other.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() :

>>> import py_compile


>>> py_compile.compile('foo.py')

.pyc foo.py __pycache__


cfile

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:

from bar import bar_var


foo_var = 1

bar.py:

from foo import foo_var


bar_var = 2

• foo

• foo

• foo

• foo bar
• bar

• bar

• bar foo ( foo )


• foo_var foo bar.foo_var = foo.foo_var
Python foo foo
import foo foo.foo_var

Guido van Rossum from <module> import ...


<module>.<name>

Jim Roskind

• import

Van Rossum import
Matthias Urlichs

2.7.4 __import__(’x.y.z’) <module ’x’> z


importlib import_module()

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)

from modname import some_objects

>>> import importlib


>>> import cls
>>> c = cls.C() # Create an instance of C
>>> importlib.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C) # isinstance is false?!?
False

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
:

>>> 1.2 - 1.0


0.19999999999999996

37
Python Frequently Asked Questions, 3.13.3

Python bug Python

CPython float C double float


53 Python C
Python C Java
:

>>> 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
:= :

while chunk := fp.read(200):


print(chunk)

PEP 572

3.7 Python list.index()


len(List)
Guido
(a) --
x*(a+b)
x*a+x*b OO
(b) len(X)
x.len() x
len() get() key()
write()
—https://mail.python.org/pipermail/python-3000/2006-November/004643.html

3.8 join()
Python 1.6
String

", ".join(['1', '2', '4', '8', '16'])

"1, 2, 4, 8, 16"

(String Constant)

split()
:

"1, 2, 4, 8, 16".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)

value = dict.setdefault(key, getvalue(key))


getvalue()

3.10 Python switch case


Python 3.10
match ... case
if... elif... elif... else

case

functions = {'a': function_1,


'b': function_2,
'c': self.method_1}

func = functions[value]
func()

getattr()

class MyVisitor:
def visit_a(self):
...

def dispatch(self, value):


method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()

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

( Jython PyPy) Python

Python CPython :

for file in very_long_list_of_files:


f = open(file)
c = f.read(1)

CPython f
GC
python with

for file in very_long_list_of_files:


with open(file) as f:
c = f.read(1)

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
:

mydict = {[1, 2]: '12'}


print(mydict[[1, 2]])

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 __eq__(self, other):


return self.the_list == other.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

o1 == o2 o1.__eq__(o2) is True hash(o1) == hash(o2)


o1.__hash__() == o2.__hash__()
hash
ListWrapper

3.21 list.sort()
list.sort()

sorted()
keys :

for key in sorted(mydict):


... # mydict[key]

3.22 Python
C++ Java

Python 2.6 abc (ABCs) isinstance()


issubclass() ABC collections.abc
ABCs Iterable Container , MutableMapping

Python
Python

stub doctest unittest

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 :

class label(Exception): pass # label

try:
...
if condition: raise label() # label
...
except label: #
pass
...

goto

3.24 r-strings

( )

r-string
Windows Windows :

f = open("/mydir/file.txt") #

DOS

dir = r"\this\is\my\dos\dir" "\\"


dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"

3.25 Python with


Python with
:

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"
]

: ”fee”, ”fiefoo” ”fum”

46 Chapter 3.
CHAPTER 4

FAQ

4.1
4.1.1 X

Python Package Index Google ”Python”

4.1.2 math.py socket.py regex.py


C C++
mathmodule.c C
Python
Python
1) Python .py)
2) C .dll .pyd .so .sl
3) C

import sys
print(sys.builtin_module_names)

4.1.3 Unix Python


#! Python
chmod +x scriptfile chmod 755 scriptfile

#!/usr/local/bin/python

Python
Python env Python
PATH Unix

47
Python Frequently Asked Questions, 3.13.3

#!/usr/bin/env python

CGI CGI PATH

/usr/bin/env env
hack Alex Rezinsky

#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""

__doc__

__doc__ = """...Whatever..."""

4.1.4 Python curses/termcap


Unix Python Modules curses
Windows Windows curses
curses curses ncurses SYSV curses
BSD curses

4.1.5 Python C onexit()


atexit C onexit()

4.1.6

handler(signum, frame)

def handler(signum, frame):


...

4.2
4.2.1 Python
Python doctest docstring docstring

unittest Java Smalltalk

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

def thread_task(name, n):


for i in range(n):
print(name, i)

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()

import threading, queue, time

#
#
#
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

GIL Sam Gross GIL Python 3.9 Python 1.5


Greg Stein GIL
Adam Olsen python-safethread GIL
30% Python 3.9
GIL
Python GIL CPU Python
threads concurrent.futures

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

with open(filename, "rb") as f:


s = f.read(8)
x, y, z = struct.unpack(">hhl", s)

> 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.4 os.popen() os.read()


os.read() os.popen()
open() os.popen()
p n p.read(n)

4.4.5 RS232
Win32, OSX, Linux, BSD, Jython, IronPython:
pyserial
Unix Mitch Chapman
https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com

4.4.6 sys.stdout stdin stderr


Python C
Python open() f.close() Python
C f

stdin stdout stderr C Python sys.stdout.


close() Python
C I/O
os.close()

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

import sys, smtplib

fromaddr = input("From: ")


toaddrs = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = ''
while True:
line = sys.stdin.readline()
( )

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()

Unix sendmail sendmail /usr/lib/


sendmail /usr/sbin/sendmail sendmail

import os

SENDMAIL = "/usr/sbin/sendmail" # sendmail


p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.com\n")
p.write("Subject: test\n")
p.write("\n") #
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
print("Sendmail exit status", sts)

4.5.4 socket connect()


select socket I/O
TCP socket connect()
.errno errno.EINPROGRESS

connect_ex() errno
connect_ex() -- 0 errno.EISCONN -- socket select.select()

asyncio Twisted

4.6
4.6.1 Python

Python DBM GDBM sqlite3

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()

NULL PyBytes_Check(), PyTuple_Check(),


PyList_Check()

Python API Include/abstract.


h PySequence_Length(), PySequence_GetItem()
Python (PyNumber_Index() )
PyMapping API

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()

”seek” 10, 0 ( ”f”):

res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);


if (res == NULL) {
... an exception occurred ...
}
else {
Py_DECREF(res);
}

PyObject_CallObject()
”()” ”(i)”

5.9 PyErr_Print() stdout / stderr

Python write() sys.stdout sys.stderr


print_error write()

io.StringIO

>>> import io, sys


>>> sys.stdout = io.StringIO()
>>> print('foo')
>>> print('hello world!')
( )

58 Chapter 5. /
Python Frequently Asked Questions, 3.13.3

( )
>>> sys.stderr.write(sys.stdout.getvalue())
foo
hello world!

>>> import io, sys


>>> class StdoutCatcher(io.TextIOBase):
... def __init__(self):
... self.data = []
... def write(self, stuff):
... self.data.append(stuff)
...
>>> import sys
>>> sys.stdout = StdoutCatcher()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write(''.join(sys.stdout.data))
foo
hello world!

5.10 C Python
:

module = PyImport_ImportModule("<modulename>");

sys.modules
sys.modules["<modulename>"]
sys.modules

attr = PyObject_GetAttrString(module, "<attrname>");

PyObject_SetAttrString()

5.11 Python C ++
” ”
Python C C++ C
Python C++
C ++ C

5.12 Setup make


shell
bug )

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.14 Linux Python


?
Python Python
Red Hat python3-devel RPM
Debian apt-get install python3-dev

5.15
Python ( if
)
Python codeop IDLE
C PyRun_InteractiveLoop() Python
PyOS_ReadlineFunctionPointer()
Modules/readline.c Parser/myreadline.c

5.16 g++ __builtin_new __pure_virtual


g ++ Python g ++ Python Modules Makefile
LINKCC g++ -shared -o mymodule.so mymodule.o

5.17 C
Python
int list dict

Boost Python Library (BPL, https://www.boost.org/libs/python/doc/index.html) C++


BPL C++

60 Chapter 5. /
CHAPTER 6

Python Windows

6.1 Windows 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

6.5 *.pyd DLL


.pyd dll foo.pyd DLL
PyInit_foo() Python import foo Python foo.pyd foo.py foo.pyc
PyInit_foo() .exe foo.lib
Windows DLL
foo.pyd PYTHONPATH Windows foo.dll foo.pyd
dll dll import foo
foo.pyd DLL __declspec(dllexport) .pyd

6.6 Python Windows


Windows Python

62 Chapter 6. Python Windows


Python Frequently Asked Questions, 3.13.3

1. Python .exe Windows Python DLL


DLL
pythonNN.dll C:\Windows\System NN Python ”33”
Python 3.3
Python pythonNN.lib
pythonNN.dll python NN.lib import lib
pythonNN.dll

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"); //

5. Python C API MSVC python.dll

1: FILE * ” ”
struct FILE
2 void SWIG

Py_INCREF(Py_None);
_resultobj = Py_None;
return _resultobj;

Py_None pythonNN.dll _Py_NoneStruct

return Py_BuildValue("");

SWIG %typemap SWIG

6. Python shell Windows Python


wxPythonWindow
Python Python i/o _
_ read() write() Python

6.7 Python tab


FAQ Python PEP 8 Python 4 Emacs
python-mode

6.7. Python tab 63


Python Frequently Asked Questions, 3.13.3

MSVC
Tools ‣ Options ‣ Tabs Default Tab size Indent size 4

Python IndentationError TabError


tabnanny

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

64 Chapter 6. Python Windows


CHAPTER 7

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

py2exe cx_Freeze Tkinter

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

...

• 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__

variable annotation, function annotation, PEP 484 PEP 526


annotations-howto
argument --
function method
• : name= **
3 5 complex() :

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

parameter PEP 362


asynchronous context manager --
__aenter__() __aexit__() async with
PEP 492
asynchronous generator --
asynchronous generator iterator async def
yield async for

await async for async with

asynchronous generator iterator --


asynchronous generator
asynchronous iterator __anext__()
yield

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

text file str

borrowed reference --
Python C API
strong reference

70 Appendix A.
Python Frequently Asked Questions, 3.13.3

borrowed reference Py_INCREF() strong reference


Py_NewRef() strong
reference
bytes-like object --
bufferobjects C-contiguous bytes bytearray array.
array memoryview

bytearray bytearray memoryview


(” ”) bytes bytes memoryview

bytecode --
Python CPython Python
.pyc
” ” virtual machine Python
Python
dis
callable --
( argument) :

callable(argument1, argument2, argumentN)

function method __call__()

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 --

• with context manager


• contextvars.Context ContextVar
context variable
• contextvars.Context current context

__enter__() __exit__() with PEP 343


context manager --
context management protocol with PEP 343
context variable --
current context contextvars.ContextVar

contiguous --
C Fortran C Fortran
C-
Fortran

coroutine --

async def PEP 492


coroutine function --
coroutine async def await async
for async with PEP 492
CPython
Python python.org ”CPython”
Jython IronPython
current context --
ContextVar ( ) context (contextvars.
Context ) ( asyncio)

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()

filesystem encoding and error handler Python PyConfig_Read()


PyConfig filesystem_encoding filesystem_errors

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 --

closure variable codeobject.


co_freevars closure variable
function --

parameter, method function


function annotation --
annotation
int int :

def sum_two_numbers(a: int, b: int) -> int:


return a + b

function
variable annotation PEP 484 annotations-howto

__future__
future , from __future__ import <feature> Python
__future__ feature

>>> import __future__


>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

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 :

>>> sum(i*i for i in range(10)) # 0, 1, 4, ... 81


285

generic function --

single dispatch functools.singledispatch() PEP 443


generic type --
type list dict

PEP 483 PEP 484 PEP 585 typing

GIL
global interpreter lock
global interpreter lock --
CPython Python bytecode
dict CPython

GIL I/O GIL


Python 3.13 GIL --disable-gil Python
-X gil=0 PYTHON_GIL=0
CPU PEP 703
hash-based pyc -- pyc
pyc-
invalidation
hashable --
__hash__()
__eq__()

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__()

for (zip(), map(), ...)


iter()
iter()
for
iterator, sequence generator
iterator --
__next__() ( next())
StopIteration
__next__() StopIteration
__iter__()
(
list) iter() for

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

attrgetter(), operator.itemgetter() operator.methodcaller()

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)

Windows ANSI ( : "cp1252")


Android VxWorks Python "utf-8"

locale.getencoding()

filesystem encoding and error handler


magic method --
special method
mapping --
collections.abc.Mapping collections.abc.
MutableMapping dict, collections.
defaultdict, collections.OrderedDict collections.Counter

meta path finder --


sys.meta_path finder path entry finders
importlib.abc.MetaPathFinder
metaclass --

Python

77
Python Frequently Asked Questions, 3.13.3

metaclasses
method --

argument ( self) function nested scope


method resolution order --
python_2.3_mro 2.3
Python
module --
Python Python
importing Python
package
module spec --
importlib.machinery.ModuleSpec

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()

random.seed() itertools.islice() random


itertools

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:

def func(foo, bar=None): ...

• positional-only
/ posonly1 posonly2:

def func(posonly1, posonly2, /, positional_or_keyword): ...

• keyword-only
*
kw_only1 kw_only2:

def func(arg, *, kw_only1, kw_only2): ...

• var-positional
* args:

def func(*args, **kwargs): ...

• var-keyword
** kwargs

argument inspect.Parameter function


PEP 362
path entry --
import path path based finder
path entry finder --
sys.path_hooks ( path entry hook) finder path entry

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 :

for piece in food:


print(piece)

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:

>>> import email.mime.text


>>> email.mime.text.__name__
'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

( )

tokenize Python token

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

Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:


pass

typing PEP 484


type hint --
annotation
Python
IDE
typing.get_type_hints()

typing PEP 484


universal newlines --
Unix '\n' Win-
dows '\r\n' Macintosh '\r' PEP 278 PEP 3116 bytes.
splitlines()
variable annotation --
annotation
:

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 Sphinx reStructuredText Sphinx Python

Python
reporting-bugs

• Fred L. Drake, Jr. Python


• reStructuredText Docutils Docutils
• Fredrik Lundh Alternative Python Reference Sphinx

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

(1) GPL GPL Python GPL Python


GPL Python

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

C.2.1 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2


1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
the Individual or Organization ("Licensee") accessing and otherwise using this
software ("Python") in source or binary form and its associated documentation.

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.

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee hereby
agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.


PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON


FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship


of agency, partnership, or joint venture between PSF and Licensee. This License
Agreement does not grant permission to use PSF trademarks or trade name in a
trademark sense to endorse or promote products or services of Licensee, or any
third party.

8. By copying, installing or otherwise using Python, Licensee agrees


to be bound by the terms and conditions of this License Agreement.

88 Appendix C.
Python Frequently Asked Questions, 3.13.3

C.2.2 PYTHON 2.0 BEOPEN.COM


BEOPEN PYTHON 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
("Licensee") accessing and otherwise using this software in source or binary
form and its associated documentation ("the Software").

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.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.


BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

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.

5. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects


by the law of the State of California, excluding conflict of law provisions.
Nothing in this License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between BeOpen and Licensee. This License
Agreement does not grant permission to use BeOpen trademarks or trade names in a
trademark sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions
granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be


bound by the terms and conditions of this License Agreement.

C.2.3 PYTHON 1.6.1 CNRI


1. This LICENSE AGREEMENT is between the Corporation for National Research
Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
("CNRI"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 1.6.1 software in source or binary form and its
associated documentation.

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".

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to Python 1.6.1.

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.

6. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property


law of the United States, including without limitation the federal copyright
law, and, to the extent such U.S. federal law does not apply, by the law of the
Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed
under the GNU General Public License (GPL), the law of the Commonwealth of
Virginia shall govern this License Agreement only as to issues arising under or
with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in
this License Agreement shall be deemed to create any relationship of agency,
partnership, or joint venture between CNRI and Licensee. This License Agreement
does not grant permission to use CNRI trademarks or trade name in a trademark
sense to endorse or promote products or services of Licensee, or any third
party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing


or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

C.2.4 PYTHON 0.9.0 1.2 CWI


Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands. All rights reserved.

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.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM 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
( )

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.

C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTA-


TION
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

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.1 Mersenne Twister


random _random C http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/
MT2002/emt19937ar.html :
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)


or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The names of its contributors may not be used to endorse or promote


products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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
( )

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.

Any feedback is very welcome.


http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)

C.3.2
socket getaddrinfo() getnameinfo() WIDE : https://www.wide.ad.jp/
Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.

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

All Rights Reserved

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 Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,


INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
( )

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 :

Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>

All Rights Reserved

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
Timothy O'Malley not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley 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
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

C.3.5
trace :

portions copyright 2001, Autonomous Zones Industries, Inc., all rights...


err... reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:zooko@zooko.com

Copyright 2000, Mojam Media, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.


Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.

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.6 UUencode UUdecode


uu :

Copyright 1994 by Lance Ellinghouse


Cathedral City, California Republic, United States of America.
All Rights Reserved
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 Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM 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 ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:


- Use binascii module to do the actual line-by-line conversion
between ascii and binary. This results in a 1000-fold speedup. The C
version is still 5 times faster, though.
- Arguments more compliant with Python standard

C.3.7 XML
xmlrpc.client :

The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB


Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its


associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and


its associated documentation for any purpose and 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
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

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) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining


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.

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.9 Select kqueue


select kqueue :

Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

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>

Permission is hereby granted, free of charge, to any person obtaining 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.
</MIT License>

Original location:
https://github.com/majek/csiphash/

Solution inspired by code from:


Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)

C.3.11 strtod dtoa


Python/dtoa.c C dtoa strtod C
David M. Gay https://web.archive.org/web/20220517033456/http:
//www.netlib.org/fp/dtoa.c 2009 3 16 :
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/

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

( )

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by


the copyright owner that is granting the License.

"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.

"You" (or "Your") shall mean an individual or Legal Entity


exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical


transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or


Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object


form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including


the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity


on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
( )

C.3. 97
Python Frequently Asked Questions, 3.13.3

( )

2. Grant of Copyright License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the


Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or


Derivative Works a copy of this License; and

(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

(d) If the Work includes a "NOTICE" text file as part of its


distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

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.

5. Submission of Contributions. Unless You explicitly state otherwise,


any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

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.

7. Disclaimer of Warranty. Unless required by applicable law or


agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,


whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing


the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

C.3.13 expat
pyexpat expat --with-system-expat:

Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining


( )

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.

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.14 libffi
ctypes _ctypes C libffi
--with-system-libffi:

Copyright (c) 1996-2008 Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining


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.

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.15 zlib
zlib zlib zlib :
Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied


warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,


including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

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.

Jean-loup Gailly Mark Adler


jloup@gzip.org madler@alumni.caltech.edu

C.3.16 cfuhash
tracemalloc cfuhash :
Copyright (c) 2005 Don Owens
All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above


copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of the author nor the names of its


contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
COPYRIGHT OWNER 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.17 libmpdec
decimal _decimal C libmpdec
--with-system-libmpdec:

Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
( )

C.3. 101
Python Frequently Asked Questions, 3.13.3

( )

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

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.18 W3C C14N


test C14N 2.0 (Lib/test/xmltestdata/c14n-20/) W3C https://www.w3.org/
TR/xml-c14n2-testcases/ 3 BSD :
Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),
All Rights Reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of works must retain the original copyright notice,


this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
used to endorse or promote products derived from this work without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
OWNER 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

Permission is hereby granted, free of charge, to any person obtaining a copy


( )

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

Permission is hereby granted, free of charge, to any person obtaining


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.

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.21 Global Unbounded Sequences (GUS)


Python/qsbr.c subr_smr.c FreeBSD ”Global Unbounded Sequences”
2 BSD :
Copyright (c) 2019,2020 Jeffrey Roberson <jeff@FreeBSD.org>

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice unmodified, this list of conditions, and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

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

generator -- , 74 namespace package -- , 78


generator expression -- , 75 nested scope -- , 79
generator expression -- , 75 new-style class -- , 79
generator iterator -- , 74
generic function -- , 75 O
generic type -- , 75 object -- , 79
GIL, 75 optimized scope -- , 79
global interpreter lock -- , 75
P
H package -- , 79
hash-based pyc -- pyc, 75 parameter --
hashable -- , 75 , 12
parameter -- , 79
I PATH, 47, 48
IDLE, 75 path based finder -- , 80
immortal -- , 75 path entry -- , 79
immutable -- , 75 path entry finder -- , 79
import path -- , 76 path entry hook -- , 80
importer -- , 76 path-like object -- , 80
importing -- , 76 PEP, 80
interactive -- , 76 portion -- , 80
interpreted -- , 76 positional argument -- , 80
interpreter shutdown -- , 76 provisional API -- API, 80
iterable -- , 76 provisional package -- , 80
iterator -- , 76 Python 3000, 80
Python PEP 1, 80
K Python PEP 5, 5
key function -- , 76 Python PEP 8, 8, 31, 63
keyword argument -- , 77 Python PEP 238, 74
Python PEP 278, 83
L Python PEP 302, 77
lambda, 77 Python PEP 343, 72
LBYL, 77 Python PEP 362, 70, 79
lexical analyzer -- , 77 Python PEP 373, 4
list -- , 77 Python PEP 387, 3
list comprehension -- , 77 Python PEP 411, 80
loader -- , 77 Python PEP 420, 78, 80
locale encoding -- , 77 Python PEP 443, 75
Python PEP 483, 75
M Python PEP 484, 69, 74, 75, 83
Python PEP 492, 70, 72
magic method -- , 77
Python PEP 498, 73
mapping -- , 77
Python PEP 519, 80
meta path finder -- , 77
Python PEP 525, 70
metaclass -- , 77
Python PEP 526, 69, 83
method --
Python PEP 572, 39
, 82
Python PEP 585, 75
, 77
Python PEP 602, 4
method -- , 78
Python PEP 683, 75
method resolution order -- , 78
Python PEP 703, 51, 74, 75
module -- , 78
Python PEP 3116, 83
module spec -- , 78
Python PEP 3147, 33
MRO, 78
Python PEP 3155, 81
mutable -- , 78
PYTHON_GIL, 75
PYTHONDONTWRITEBYTECODE, 33
N Pythonic, 80
named tuple -- , 78
namespace -- , 78

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

You might also like