0% found this document useful (0 votes)
3 views154 pages

Python Tutorial

The document is a Python tutorial for version 3.14.0rc3, authored by Guido van Rossum and the Python development team. It includes a comprehensive table of contents covering various topics related to Python programming, including syntax, control flow, and functions. The tutorial is published by the Python Software Foundation and is intended for users looking to learn or enhance their Python skills.
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)
3 views154 pages

Python Tutorial

The document is a Python tutorial for version 3.14.0rc3, authored by Guido van Rossum and the Python development team. It includes a comprehensive table of contents covering various topics related to Python programming, including syntax, control flow, and functions. The tutorial is published by the Python Software Foundation and is intended for users looking to learn or enhance their Python skills.
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

Python Tutorial

3.14.0rc3

Guido van Rossum and the Python development team

01, 2025

Python Software Foundation


Email: docs@[Link]
Contents

1 3

2 Python 5
2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

3 Python 7
3.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4 15
4.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.2 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.3 range() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.4 break continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.5 else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.6 pass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.7 match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.9.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.9.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.9.6 Lambda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.9.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.9.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

5 31
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

i
5.1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2 del . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

6 41
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.1.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6.3 dir() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
6.4.1 *. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
6.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

7 49
7.1 . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
7.1.1 .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
7.1.2 format() . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
7.1.3 . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7.1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.2.2 json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

8 57
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
8.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
8.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
8.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
8.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
8.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
8.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
8.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

9 67
9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
9.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
9.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.3.2 Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
9.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
9.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
9.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
9.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
9.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

ii
9.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
9.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

10 79
10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
10.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
10.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
10.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
10.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
10.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
10.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10.12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

11 85
11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
11.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
11.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
11.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
11.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

12 91
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
12.3 pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

13 95

14 97
14.1 Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
14.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

15 99
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

16 105
16.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
16.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
16.1.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
16.1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
16.1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

A 107

B 123
B.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

C 125
C.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
C.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . 126
C.2.1 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 . . . . . . . . . . . . . 126
C.2.2 PYTHON 2.0 [Link] . . . . . . . . . . . . . . . . . . . . . 127
C.2.3 PYTHON 1.6.1 CNRI . . . . . . . . . . . . . . . . . . . . . . . . . 127
C.2.4 PYTHON 0.9.0 1.2 CWI . . . . . . . . . . . . . . . . . . . . . . 128

iii
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION . 129
C.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
C.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
C.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
C.3.4 Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
C.3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
C.3.6 UUencode UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
C.3.7 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
C.3.9 Select kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
C.3.11 strtod dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
C.3.18 W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
C.3.19 mimalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
C.3.21 Global Unbounded Sequences (GUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
C.3.22 Zstandard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

D 143

145

iv
Python Tutorial, 3.14.0rc3

Python

Python
Python

Python [Link] Python


Python Python

Python C C++ C Python


Python
Python
Python

library-index reference-index C C++


extending-index c-api-index Python
Python
Python Python
library-index

Contents 1
Python Tutorial, 3.14.0rc3

2 Contents
CHAPTER 1

C/C++/Java

Python
Unix shell Windows shell
GUI C/C++/Java
Python Windows, macOS Unix

Python
shell Python C
Python Awk Perl
Python
Python Python
Python I/O
Tk
Python

Python C C++ Java





Python C
Python
Python C
BBC Monty Python Python
Monty Python

3
Python Tutorial, 3.14.0rc3

Python
Python

Python

4 Chapter 1.
CHAPTER 2

Python

2.1
Python /usr/local/bin/python3.14 /usr/local/bin
Unix shell

python3.14

1
shell Python
Python /usr/local/python
Windows Microsoft Store Python python3.14
[Link] py setting-envvars Python
Unix Control-D Windows Control-Z
0 quit()

GNU Readline
Python Control-P
^P

Unix Shell tty

python -c command [arg] ... command


shell -c Python shell
command
Python python -m module [arg] ... module

-i

using-on-general
1 Unix Python 2.x Python 3.x python

5
Python Tutorial, 3.14.0rc3

2.1.1
sys argv
import sys sys.
argv[0] '-' [Link][0] '-' -c command
[Link][0] '-c' -m module [Link][0]
-c command -m module [Link]

2.1.2
tty interactive mode
>>>
...

$ python3.14
Python 3.14 (default, April 4 2024, 09:25:04)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

if

>>> the_world_is_flat = True


>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!

2.2
2.2.1
Python UTF-8
ASCII
UTF-8

# -*- coding: encoding -*-

encoding Python codecs


Windows-1252

# -*- coding: cp1252 -*-

UNIX ”shebang”

#!/usr/bin/env python3
# -*- coding: cp1252 -*-

6 Chapter 2. Python
CHAPTER 3

Python

»> ...

Python #
# #
Python

#
spam = 1 #
# ...
text = "# "

3.1 Python
Python >>>

3.1.1
+,
-, * / (()) :

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 #
1.6

2 4 20 int 5.0 1.6 float

( /) floor division //
%:

7
Python Tutorial, 3.14.0rc3

>>> 17 / 3 #
5.666666666666667
>>>
>>> 17 // 3 #
5
>>> 17 % 3 # %
2
>>> 5 * 3 + 2 # * +
17

1
Python **

>>> 5 ** 2 # 5
25
>>> 2 ** 7 # 2 7
128

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

>>> n #
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

Python

>>> 4 * 3.75 - 1
14.0

_ Python

>>> tax = 12.5 / 100


>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

int float Python Decimal Fraction Python


j J 3+5j

3.1.2
Python str ”!”, ”rabbit”,
”Paris”, ”Got your back.” . ”Yay! :)” ('...')
2
("...")
1 ** - , -3**2 -(3**2) -9 9, (-3)**2
2 \n '...' "..."
" \'

8 Chapter 3. Python
Python Tutorial, 3.14.0rc3

>>> 'spam eggs' #


'spam eggs'
>>> "Paris rabbit got your back :)! Yay!" #
'Paris rabbit got your back :)! Yay!'
>>> '1975' #
'1975'

\
:
>>> 'doesn\'t' # \' ...
"doesn't"
>>> "doesn't" # ...
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

Python shell print()


:
>>> s = 'First line.\nSecond line.' # \n
>>> s # print()
'First line.\nSecond line.'
>>> print(s) # print() \n
First line.
Second line.

\ r

>>> print('C:\some\name') # \n
C:\some
ame
>>> print(r'C:\some\name') # r
C:\some\name

\ FAQ

: """...""" '''...'''
\ :
>>> print("""\
... Usage: thingy [OPTIONS]
... -h Display this usage message
... -H hostname Hostname to connect to
... """)
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

>>>

+ *

>>> # 3 'un' 'ium'


>>> 3 * 'un' + 'ium'
'unununium'

3.1. Python 9
Python Tutorial, 3.14.0rc3

>>> 'Py' 'thon'


'Python'

>>> text = ('Put several strings within parentheses '


... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

>>> prefix = 'Py'


>>> prefix 'thon' #
File "<stdin>", line 1
prefix 'thon'
^^^^^^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^^^^^
SyntaxError: invalid syntax

>>> prefix + 'thon'


'Python'

0
>>> word = 'Python'
>>> word[0] # 0
'P'
>>> word[5] # 5
'n'

>>> word[-1] #
'n'
>>> word[-2] #
'o'
>>> word[-6]
'P'

-0 0 -1
:
>>> word[0:2] # 0 ( ) 2 ( )
'Py'
>>> word[2:5] # 2 ( ) 5 ( )
'tho'

0
>>> word[:2] # 2 ( )
'Py'
>>> word[4:] # 4 ( )
'on'
>>> word[-2:] # ( )
'on'

10 Chapter 3. Python
Python Tutorial, 3.14.0rc3

s[:i] + s[i:] s

>>> word[:2] + word[2:]


'Python'
>>> word[:4] + word[4:]
'Python'

0 n
n

+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

0...6 i j i j

word[1:3]
2

>>> word[42] # word 6


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

>>> word[4:42]
'on'
>>> word[42:]
''

Python immutable

>>> word[0] = 'J'


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> 'J' + word[1:]


'Jython'
>>> word[:2] + 'py'
'Pypy'

len()

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

3.1. Python 11
Python Tutorial, 3.14.0rc3

textseq

string-methods

f-strings

formatstrings
[Link]()

old-string-formatting
%

3.1.3
Python

>>> squares = [1, 4, 9, 16, 25]


>>> squares
[1, 4, 9, 16, 25]

sequence

>>> squares[0] #
1
>>> squares[-1]
25
>>> squares[-3:] #
[9, 16, 25]

>>> squares + [36, 49, 64, 81, 100]


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

immutable , mutable

>>> cubes = [1, 8, 27, 65, 125] #


>>> 4 ** 3 # 4 64 65
64
>>> cubes[3] = 64 #
>>> cubes
[1, 8, 27, 64, 125]

[Link]()
:

>>> [Link](216) # 6
>>> [Link](7 ** 3) # 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Python
:

>>> rgb = ["Red", "Green", "Blue"]


>>> rgba = rgb
>>> id(rgb) == id(rgba) #
( )

12 Chapter 3. Python
Python Tutorial, 3.14.0rc3

( )
True
>>> [Link]("Alph")
>>> rgb
["Red", "Green", "Blue", "Alph"]

>>> correct_rgba = rgba[:]


>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba
["Red", "Green", "Blue", "Alph"]

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> #
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> #
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> #
>>> letters[:] = []
>>> letters
[]

len()

>>> letters = ['a', 'b', 'c', 'd']


>>> len(letters)
4

>>> a = ['a', 'b', 'c']


>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2
Python
:

>>> #
>>> #
>>> a, b = 0, 1
>>> while a < 10:
( )

3.2. 13
Python Tutorial, 3.14.0rc3

( )
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8

• a b 0 1

• while a < 10 Python C

C <
> == <= ) >= !=

• Python

• print()

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

end ,

>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

14 Chapter 3. Python
CHAPTER 4

while Python

4.1 if
if

>>> x = int(input("Please enter an integer: "))


Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...

elif else ’elif’ ’else if’


if ... elif ... elif ... switch case
match match

4.2 for
Python for C Pascal Python for Pascal
C

>>> #
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
( )

15
Python Tutorial, 3.14.0rc3

( )
cat 3
window 6
defenestrate 12

#
users = {'Hans': 'active', 'Éléonore': 'inactive', ' ': 'active'}

#
for user, status in [Link]().items():
if status == 'inactive':
del users[user]

#
active_users = {}
for user, status in [Link]():
if status == 'active':
active_users[user] = status

4.3 range()
range()

>>> for i in range(5):


... print(i)
...
0
1
2
3
4

range(10) 10 10
range 0

>>> list(range(5, 10))


[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))


[0, 3, 6, 9]

>>> list(range(-10, -100, -30))


[-10, -40, -70]

range() len()

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']


>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

enumerate()

16 Chapter 4.
Python Tutorial, 3.14.0rc3

range
>>> range(10)
range(0, 10)

range()

iterable for
sum()

>>> sum(range(4)) # 0 + 1 + 2 + 3
6

list()

4.4 break continue


break for while :
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(f"{n} equals {x} * {n//x}")
... break
...
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3

continue :
>>> for num in range(2, 10):
... if num % 2 == 0:
... print(f"Found an even number {num}")
... continue
... print(f"Found an odd number {num}")
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

4.5 else
for while break else break
else
for else break
while

break else
return else

for

4.4. break continue 17


Python Tutorial, 3.14.0rc3

>>> for n in range(2, 10):


... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... #
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

else for if

else if if/if/if/else
if break
else

else try else if try


else else break try

4.6 pass
pass

>>> while True:


... pass # (Ctrl+C)
...

>>> class MyEmptyClass:


... pass
...

pass pass

>>> def initlog(*args):


... pass #
...

... pass Python


...
bltin-ellipsis-object

4.7 match
match case C
Java JavaScript switch Rust Haskell

case

18 Chapter 4.
Python Tutorial, 3.14.0rc3

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

case 401 | 403 | 404:


return "Not allowed"

# point (x, y)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")

point
(x, y) = point

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")

dataclass
__match_args__ (”x”, ”y”)
y var

4.7. match 19
Python Tutorial, 3.14.0rc3

Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)

match var [Link]


x= y= ”(...)” Point

Point Point __match_args__

class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y

match points:
case []:
print("No points")
case [Point(0, 0)]:
print("The origin")
case [Point(x, y)]:
print(f"Single point {x}, {y}")
case [Point(0, y1), Point(0, y2)]:
print(f"Two on the Y axis at {y1}, {y2}")
case _:
print("Something else")

if match case

match point:
case Point(x, y) if x == y:
print(f"Y=X at {x}")
case Point(x, y):
print(f"Not on the diagonal")

• [x, y, *rest] (x, y, *rest)


* _ (x, y, *_)
• {"bandwidth": b, "latency": l} "bandwidth" "latency"
**rest **_

• as

case (Point(x1, y1), Point(x2, y2) as p2): ...

p2

• True False None id


from enum import Enum


class Color(Enum):
( )

20 Chapter 4.
Python Tutorial, 3.14.0rc3

( )
RED = 'red'
GREEN = 'green'
BLUE = 'blue'

color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))

match color:
case [Link]:
print("I see red!")
case [Link]:
print("Grass is green")
case [Link]:
print("I'm feeling the blues :(")

PEP 636

4.8

>>> def fib(n): # n


... """Print a Fibonacci series less than n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> #
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

def

docstring
Python

global
nonlocal

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

fib
return None ( )
None print() :
1

4.8. 21
Python Tutorial, 3.14.0rc3

>>> fib(0)
>>> print(fib(0))
None

>>> def fib2(n): # n


... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... [Link](a) #
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) #
>>> f100 #
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Python
• return return None
None
• [Link](a) result
[Link] obj methodname

append()
result = result + [a]

4.9

4.9.1

def ask_ok(prompt, retries=4, reminder='Please try again!'):


while True:
reply = input(prompt)
if reply in {'y', 'ye', 'yes'}:
return True
if reply in {'n', 'no', 'nop', 'nope'}:
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)

• ask_ok('Do you really want to quit?')

• ask_ok('OK to overwrite the file?', 2)

• ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

in

22 Chapter 4.
Python Tutorial, 3.14.0rc3

i = 5

def f(arg=i):
print(arg)

i = 6
f()

def f(a, L=[]):


[Link](a)
return L

print(f(1))
print(f(2))
print(f(3))

[1]
[1, 2]
[1, 2, 3]

def f(a, L=None):


if L is None:
L = []
[Link](a)
return L

4.9.2
kwarg=value

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):


print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")

voltage state, action type

parrot(1000) # 1
parrot(voltage=1000) # 1
parrot(voltage=1000000, action='VOOOOOM') # 2
parrot(action='VOOOOOM', voltage=1000000) # 2
parrot('a million', 'bereft of life', 'jump') # 3
parrot('a thousand', state='pushing up the daisies') # 1 1

parrot() #
parrot(voltage=5.0, 'dead') #
parrot(110, voltage=220) #
parrot(actor='John Cleese') #

4.9. 23
Python Tutorial, 3.14.0rc3

actor parrot
parrot(voltage=1000)

>>> def function(a):


... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

**name typesmapping
**name *name *name
**name *name

def cheeseshop(kind, *arguments, **keywords):


print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])

cheeseshop("Limburger", "It's very runny, sir.",


"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")

-- Do you have any Limburger ?


-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

4.9.3
Python

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):


----------- ---------- ----------
| | |
| |
| -
--

24 Chapter 4.
Python Tutorial, 3.14.0rc3

/ *

/ *

/ /
/

/ *

>>> def standard_arg(arg):


... print(arg)
...
>>> def pos_only_arg(arg, /):
... print(arg)
...
>>> def kwd_only_arg(*, arg):
... print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
... print(pos_only, standard, kwd_only)

standard_arg

>>> standard_arg(2)
2

>>> standard_arg(arg=2)
2

pos_only_arg /

>>> pos_only_arg(1)
1

>>> pos_only_arg(arg=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments:
,→'arg'

kwd_only_arg *

>>> kwd_only_arg(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
( )

4.9. 25
Python Tutorial, 3.14.0rc3

( )

>>> kwd_only_arg(arg=3)
3

>>> combined_example(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given

>>> combined_example(1, 2, kwd_only=3)


1 2 3

>>> combined_example(1, standard=2, kwd_only=3)


1 2 3

>>> combined_example(pos_only=1, standard=2, kwd_only=3)


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword␣
,→arguments: 'pos_only'

kwds name name

def foo(name, **kwds):


return 'name' in kwds

True 'name'

>>> foo(1, **{'name': 2})


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>

/ name 'name'

>>> def foo(name, /, **kwds):


... return 'name' in kwds
...
>>> foo(1, **{'name': 2})
True

**kwds

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

• API API

26 Chapter 4.
Python Tutorial, 3.14.0rc3

4.9.4

def write_multiple_items(file, separator, *args):


[Link]([Link](args))

variadic *args

>>> def concat(*args, sep="/"):


... return [Link](args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'[Link]'

4.9.5
range()
start stop *

>>> list(range(3, 6)) #


[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) #
[3, 4, 5]

**

>>> def parrot(voltage, state='a stiff', action='voom'):


... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

4.9.6 Lambda
lambda lambda a, b: a+b Lambda

lambda

>>> def make_incrementor(n):


... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

lambda [Link]()
key lambda :

4.9. 27
Python Tutorial, 3.14.0rc3

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> [Link](key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

4.9.7

Python Python

>>> def my_function():


... """
...
...
... """
... pass
...
>>> print(my_function.__doc__)

4.9.8
PEP 3107 PEP 484
__annotations__

-> def
:

>>> def f(ham: str, eggs: str = 'eggs') -> str:


... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

4.10
Python

28 Chapter 4.
Python Tutorial, 3.14.0rc3

Python PEP 8 Python

• 4
4

• 79




• a = f(1, 2) + g(3, 4)

• UpperCamelCase
lowercase_with_underscores self ( )
• Python UTF-8 ASCII

• ASCII

4.10. 29
Python Tutorial, 3.14.0rc3

30 Chapter 4.
CHAPTER 5

5.1

[Link](x)
a[len(a):] = [x]
[Link](iterable)
iterable a[len(a):] = iterable

[Link](i, x)
[Link](0, x)
[Link](len(a), x) [Link](x)

[Link](x)
x ValueError

[]
[Link]( i )
[Link]()
IndexError
[Link]()
del a[:]

[ [
[Link](x , start , end ]])
x ValueError

start end
start
[Link](x)
x
[Link](* (Keyword-only parameters separator (PEP 3102)), key=None, reverse=False)
sorted()

31
Python Tutorial, 3.14.0rc3

[Link]()

[Link]()
a[:]

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']


>>> [Link]('apple')
2
>>> [Link]('tangerine')
0
>>> [Link]('banana')
3
>>> [Link]('banana', 4) # 4 banana
6
>>> [Link]()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> [Link]('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> [Link]()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> [Link]()
'pear'

insert, remove sort --


1
None Python
[None, 'hello', 10]
None
3+4j < 5+7j

5.1.1

append() pop() :

>>> stack = [3, 4, 5]


>>> [Link](6)
>>> [Link](7)
>>> stack
[3, 4, 5, 6, 7]
>>> [Link]()
7
>>> stack
[3, 4, 5, 6]
>>> [Link]()
6
>>> [Link]()
5
>>> stack
[3, 4]

1 d->insert("a")->remove("b")->sort();

32 Chapter 5.
Python Tutorial, 3.14.0rc3

5.1.2

[Link]

>>> from collections import deque


>>> queue = deque(["Eric", "John", "Michael"])
>>> [Link]("Terry") # Terry
>>> [Link]("Graham") # Graham
>>> [Link]() #
'Eric'
>>> [Link]() #
'John'
>>> queue #
deque(['Michael', 'Terry', 'Graham'])

5.1.3

>>> squares = []
>>> for x in range(10):
... [Link](x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

squares = list(map(lambda x: x**2, range(10)))

squares = [x**2 for x in range(10)]

for for
if for if

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]


[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... [Link]((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

for if

5.1. 33
Python Tutorial, 3.14.0rc3

(x, y)

>>> vec = [-4, -2, 0, 2, 4]


>>> #
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> #
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> #
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> #
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [[Link]() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # ( , ) 2
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> #
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1
[x, x**2 for x in range(6)]
^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?
>>> # 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> from math import pi


>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4

3x4 3 4

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]

>>> [[row[i] for row in matrix] for i in range(4)]


[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

for
:

>>> transposed = []
>>> for i in range(4):
... [Link]([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

34 Chapter 5.
Python Tutorial, 3.14.0rc3

>>> transposed = []
>>> for i in range(4):
... # 3
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... [Link](transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

zip()

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

5.2 del
del pop() del

:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del

>>> del a

a del

5.3
typesseq Python

>>> t = 12345, 54321, 'hello!'


>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> #
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> #
( )

5.2. del 35
Python Tutorial, 3.14.0rc3

( )
>>> t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> #
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

immutable
namedtuples mutable

0 1

>>> empty = ()
>>> singleton = 'hello', # <--
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

t = 12345, 54321, 'hello!' 12345, 54321 'hello!'

>>> x, y, z = t

5.4
Python

set() set() {} {}

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}


>>> print(basket) #
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket #
True
>>> 'crabgrass' in basket
False

>>> #
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
( )

36 Chapter 5.
Python Tutorial, 3.14.0rc3

( )
>>> a # a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # a b
{'r', 'd', 'b'}
>>> a | b # a b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # a b
{'a', 'c'}
>>> a ^ b # a b
{'r', 'd', 'b', 'm', 'z', 'l'}

>>> a = {x for x in 'abracadabra' if x not in 'abc'}


>>> a
{'r', 'd'}

5.5
Python ( typesmapping)

append() extend()

{}

del

list(d) sorted(d)
in

>>> tel = {'jack': 4098, 'sape': 4139}


>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

dict()

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])


{'sape': 4139, 'guido': 4127, 'jack': 4098}

5.5. 37
Python Tutorial, 3.14.0rc3

>>> {x: x**2 for x in (2, 4, 6)}


{2: 4, 4: 16, 6: 36}

>>> dict(sape=4139, guido=4127, jack=4098)


{'sape': 4139, 'guido': 4127, 'jack': 4098}

5.6
items()

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}


>>> for k, v in [Link]():
... print(k, v)
...
gallahad the pure
robin the brave

enumerate()

>>> for i, v in enumerate(['tic', 'tac', 'toe']):


... print(i, v)
...
0 tic
1 tac
2 toe

zip()

>>> questions = ['name', 'quest', 'favorite color']


>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

reversed()

>>> for i in reversed(range(1, 10, 2)):


... print(i)
...
9
7
5
3
1

sorted()

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']


>>> for i in sorted(basket):
... print(i)
...
apple
apple
banana
orange
( )

38 Chapter 5.
Python Tutorial, 3.14.0rc3

( )
orange
pear

set() sorted() set()

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']


>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear

>>> import math


>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not [Link](value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

5.7
while if
in not in
is is not

a < b == c a b b c

and or not
not or A and not B
or C (A and (not B)) or C
and or
A C B A and B and C C

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'


>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

Python C := C
== =

5.8

5.7. 39
Python Tutorial, 3.14.0rc3

Unicode

(1, 2, 3) < (1, 2, 4)


[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)

< >
0 0.0
TypeError

40 Chapter 5.
CHAPTER 6

Python Python

Python

Python .py
__name__ [Link]

def fib(n):
"""Write Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()

def fib2(n):
"""Return Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
[Link](a)
a, b = b, a+b
return result

Python

>>> import fibo

fibo namespace Python


fibo :

41
Python Tutorial, 3.14.0rc3

>>> [Link](1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

>>> fib = [Link]


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1
import
1
( )

[Link]

import

import
:

>>> from fibo import fib, fib2


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

fibo

>>> from fibo import *


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

as as

>>> import fibo as fib


>>> [Link](500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

import fibo fib

from

42 Chapter 6.
Python Tutorial, 3.14.0rc3

>>> from fibo import fib as fibonacci


>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

[Link]() import importlib; importlib.


reload(modulename)

6.1.1
Python

python [Link] <arguments>

__name__ "__main__"

if __name__ == "__main__":
import sys
fib(int([Link][1]))

main

$ python [Link] 50
0 1 1 2 3 5 8 13 21 34

>>> import fibo


>>>

6.1.2
spam sys.
builtin_module_names [Link]
[Link] [Link] :

• PYTHONPATH shell PATH
• site-packages site

sys-path-init

Python [Link]

6.1. 43
Python Tutorial, 3.14.0rc3

6.1.3 Python
Python __pycache__ [Link].
pyc version Python CPython 3.3 [Link]
__pycache__/[Link] Python

Python

Python

• Python -O -OO -O -OO


__doc__
opt-

• .pyc .py .pyc

• compileall .pyc
• PEP 3147

6.2
Python Python ” ”

winreg Windows sys


Python sys.ps1 sys.ps2 :

>>> import sys


>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>

[Link] PYTHONPATH
PYTHONPATH

>>> import sys


>>> [Link]('/ufs/guido/lib/python')

6.3 dir()
dir()

>>> import fibo, sys


>>> dir(fibo)
( )

44 Chapter 6.
Python Tutorial, 3.14.0rc3

( )
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
'_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
'warnoptions']

dir()

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = [Link]
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

dir() builtins

>>> import builtins


>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
( )

6.3. dir() 45
Python Tutorial, 3.14.0rc3

( )
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']

6.4
Python A.B A
B
NumPy Pillow

.wav .aiff .au

sound/
__init__.py sound
formats/
__init__.py
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
...
effects/
__init__.py
[Link]
[Link]
[Link]
...
filters/
__init__.py
[Link]
[Link]
[Link]
...

Python [Link]

__init__.py Python namespace package


string
__init__.py
__all__

import [Link]

[Link]

[Link](input, output, delay=0.7, atten=4)

46 Chapter 6.
Python Tutorial, 3.14.0rc3

from [Link] import echo

echo :

[Link](input, output, delay=0.7, atten=4)

Import

from [Link] import echofilter

echo echofilter() :

echofilter(input, output, delay=0.7, atten=4)

from package import item item


import item
item item ImportError

import [Link] item

6.4.1 *
from [Link] import *

import __init__.py
__all__ from package import *
*
sound/effects/__init__.py

__all__ = ["echo", "surround", "reverse"]

from [Link] import * [Link]


sound/effects/__init__.py
reverse from [Link] import * echo surround
reverse reverse :

__all__ = [
"echo", # '[Link]'
"surround", # '[Link]'
"reverse", # !!! 'reverse' !!!
]

def reverse(msg: str): # <-- '[Link]'


return msg[::-1] # 'from [Link] import *'

__all__ from [Link] import * [Link]


[Link] __init__.py
__init__.py
import :

import [Link]
import [Link]
from [Link] import *

echo surround from...import


[Link] __all__

6.4. 47
Python Tutorial, 3.14.0rc3

import *

from package import specific_submodule

6.4.2
sound
[Link] [Link] echo from
[Link] import echo
from module import name import
surround :

from . import echo


from .. import formats
from ..filters import equalizer

Python

6.4.3
__path__ sequence
__init__.py

48 Chapter 6.
CHAPTER 7

7.1
: print()
write() [Link]

• / f F
{ } Python

>>> year = 2016


>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

• [Link]() { }

>>> yes_votes = 42_572_654


>>> total_votes = 85_705_149
>>> percentage = yes_votes / total_votes
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'

Notice how the yes_votes


percentage 100 2 ( formatspec )

repr() str()

str() repr()
SyntaxError str() repr()

49
Python Tutorial, 3.14.0rc3

>>> s = 'Hello, world.'


>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

string [Link]
$x

7.1.1
f- f F {expression}
Python
pi

>>> import math


>>> print(f'The value of pi is approximately {[Link]:.3f}.')
The value of pi is approximately 3.142.

':'

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}


>>> for name, phone in [Link]():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678

'!a' ascii() '!s' str() '!r' repr()

>>> animals = 'eels'


>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

50 Chapter 7.
Python Tutorial, 3.14.0rc3

>>> bugs = 'roaches'


>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'

= formatspec

7.1.2 format()
[Link]()

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))


We are the knights who say "Ni!"

[Link]()
[Link]()

>>> print('{0} and {1}'.format('spam', 'eggs'))


spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

[Link]()

>>> print('This {food} is {adjective}.'.format(


... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',


... other='Georg'))
The story of Bill, Manfred, and Georg.

'[]'

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}


>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
... 'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

table **

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}


>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

vars() :
>>> table = {k: str(v) for k, v in vars().items()}
>>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in [Link]()])
>>> print([Link](**table))
__name__: __main__; __doc__: None; __package__: None; __loader__: ...

:
>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
( )

7.1. 51
Python Tutorial, 3.14.0rc3

( )
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

[Link]() formatstrings

7.1.3

>>> for x in range(1, 11):


... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # 'end'
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

print()

[Link]()
[Link]() [Link]()

[Link](n)[:n]

[Link]()

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

7.1.4
% ( ) format % values ( format )
format % values :

>>> import math


>>> print('The value of pi is approximately %5.3f.' % [Link])
The value of pi is approximately 3.142.

old-string-formatting

52 Chapter 7.
Python Tutorial, 3.14.0rc3

7.2
open() file object open(filename, mode,
encoding=None)

>>> f = open('workfile', 'w', encoding="utf-8")

mode 'r'
'w' 'a'
'r+' mode
'r'

text mode
encoding encoding open() UTF-8
encoding="utf-8"
'b' binary mode bytes
encoding
Unix \n, Windows \r\n \n
\n
JPEG EXE

with
with try-finally

>>> with open('workfile', encoding="utf-8") as f:


... read_data = [Link]()

>>> #
>>> [Link]
True

with [Link]()

[Link]() with [Link]() ** **


[Link]()

with [Link]()

>>> [Link]()
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.

7.2.1
f

[Link](size)
size size size
size size size
[Link]() ''

>>> [Link]()
'This is the entire file.\n'
( )

7.2. 53
Python Tutorial, 3.14.0rc3

( )
>>> [Link]()
''

[Link]() \n
[Link]()
'\n'

>>> [Link]()
'This is the first line of the file.\n'
>>> [Link]()
'Second line of the file\n'
>>> [Link]()
''

>>> for line in f:


... print(line, end='')
...
This is the first line of the file.
Second line of the file

list(f) [Link]()

[Link](string) string

>>> [Link]('This is a test\n')


15

>>> value = ('the answer', 42)


>>> s = str(value) #
>>> [Link](s)
18

[Link]()

[Link](offset, whence) offset


whence whence 0 1 2
whence 0

>>> f = open('workfile', 'rb+')


>>> [Link](b'0123456789abcdef')
16
>>> [Link](5) # 6
5
>>> [Link](1)
b'5'
>>> [Link](-3, 2) # 3
13
>>> [Link](1)
b'd'

b seek(0, 2)
offset [Link]() 0 offset

isatty() truncate()

54 Chapter 7.
Python Tutorial, 3.14.0rc3

7.2.2 json
read()
int() '123' 123

Python JSON (JavaScript Object Notation)


json Python
serializing deserializing

JSON

JSON

>>> import json


>>> x = [1, 'simple', 'list']
>>> [Link](x)
'[1, "simple", "list"]'

dumps() dump() text file f text file

[Link](x, f)

f binary file text file

x = [Link](f)

JSON UTF-8 JSON text file


encoding="utf-8"

JSON
json

pickle -

JSON pickle Python Python

pickle

7.2. 55
Python Tutorial, 3.14.0rc3

56 Chapter 7.
CHAPTER 8

8.1
Python

>>> while True print('Hello world')


File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid syntax

print() (':')
( <stdin>)

8.2

Python

>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
4 + spam*3
^^^^
NameError: name 'spam' is not defined
( )

57
Python Tutorial, 3.14.0rc3

( )
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
'2' + 2
~~~~^~~
TypeError: can only concatenate str (not "int") to str

ZeroDivisionError NameError TypeError

bltin-exceptions

8.3

Control-C KeyboardInterrupt

>>> while True:


... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...

try

• try try except

• except try
• try except
except try/except
• except try

try except
try try except
:
... except (RuntimeError, TypeError, NameError):
... pass

except ---
except B, C, D:
class B(Exception):
pass

class C(B):
pass

class D(C):
( )

58 Chapter 8.
Python Tutorial, 3.14.0rc3

( )
pass

for cls in [B, C, D]:


try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")

except except B B, B, B ---


except

except
args __str__()
.args

>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) #
... print([Link]) # .args
... print(inst) # __str__ args
... #
... x, y = [Link] # args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

__str__() (’detail’)
BaseException Exception
Exception [Link]()
SystemExit KeyboardInterrupt

Exception

Exception :

import sys

try:
f = open('[Link]')
s = [Link]()
i = int([Link]())
except OSError as err:
print("OS error:", err)
except ValueError:
print("Could not convert data to an integer.")
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
raise

8.3. 59
Python Tutorial, 3.14.0rc3

try ... except else except


try :

for arg in [Link][1:]:


try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len([Link]()), 'lines')
[Link]()

else try try ... except

try try
:

>>> def this_fails():


... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero

8.4
raise

>>> raise NameError('HiThere')


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
raise NameError('HiThere')
NameError: HiThere

raise BaseException
Exception

raise ValueError # 'raise ValueError()'

raise

>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise NameError('HiThere')
NameError: HiThere

60 Chapter 8.
Python Tutorial, 3.14.0rc3

8.5
except
:
>>> try:
... open("[Link]")
... except OSError:
... raise RuntimeError("unable to handle error")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
open("[Link]")
~~~~^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):


File "<stdin>", line 4, in <module>
raise RuntimeError("unable to handle error")
RuntimeError: unable to handle error

raise from :
# exc None
raise RuntimeError from exc

>>> def func():


... raise ConnectionError
...
>>> try:
... func()
... except ConnectionError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
func()
~~~~^^
File "<stdin>", line 2, in func
ConnectionError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):


File "<stdin>", line 4, in <module>
raise RuntimeError('Failed to open database') from exc
RuntimeError: Failed to open database

from None :
>>> try:
... open('[Link]')
... except OSError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
raise RuntimeError from None
( )

8.5. 61
Python Tutorial, 3.14.0rc3

( )
RuntimeError

bltin-exceptions

8.6
Python
Exception

Error

8.7
try

>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise KeyboardInterrupt
KeyboardInterrupt

finally finally try try


finally

• try except
except finally

• except else finally

• finally break continue return


3.14 SyntaxWarning ( PEP 765)
• try break, continue return finally break
continue return
• finally return finally return
try return 3.14
SyntaxWarning PEP 765

>>> def bool_return():


... try:
... return True
... finally:
... return False
...
>>> bool_return()
False

62 Chapter 8.
Python Tutorial, 3.14.0rc3

>>> def divide(x, y):


... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
divide("2", "1")
~~~~~~^^^^^^^^^^
File "<stdin>", line 3, in divide
result = x / y
~~^~~
TypeError: unsupported operand type(s) for /: 'str' and 'str'

finally except TypeError


finally

finally

8.8

for line in open("[Link]"):


print(line, end="")

with

with open("[Link]") as f:
for line in f:
print(line, end="")

8.9

ExceptionGroup

8.8. 63
Python Tutorial, 3.14.0rc3

>>> def f():


... excs = [OSError('error 1'), SystemError('error 2')]
... raise ExceptionGroup('there were problems', excs)
...
>>> f()
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| f()
| ~^^
| File "<stdin>", line 3, in f
| raise ExceptionGroup('there were problems', excs)
| ExceptionGroup: there were problems (2 sub-exceptions)
+-+---------------- 1 ----------------
| OSError: error 1
+---------------- 2 ----------------
| SystemError: error 2
+------------------------------------
>>> try:
... f()
... except Exception as e:
... print(f'caught {type(e)}: e')
...
caught <class 'ExceptionGroup'>: e
>>>

except* except
except*

>>> def f():


... raise ExceptionGroup(
... "group1",
... [
... OSError(1),
... SystemError(2),
... ExceptionGroup(
... "group2",
... [
... OSError(3),
... RecursionError(4)
... ]
... )
... ]
... )
...
>>> try:
... f()
... except* OSError as e:
... print("There were OSErrors")
... except* SystemError as e:
... print("There were SystemErrors")
...
There were OSErrors
There were SystemErrors
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| f()
| ~^^
| File "<stdin>", line 2, in f
| raise ExceptionGroup(
| ...<12 lines>...
| )
( )

64 Chapter 8.
Python Tutorial, 3.14.0rc3

( )
| ExceptionGroup: group1 (1 sub-exception)
+-+---------------- 1 ----------------
| ExceptionGroup: group2 (1 sub-exception)
+-+---------------- 1 ----------------
| RecursionError: 4
+------------------------------------
>>>

>>> excs = []
... for test in tests:
... try:
... [Link]()
... except Exception as e:
... [Link](e)
...
>>> if excs:
... raise ExceptionGroup("Test Failures", excs)
...

8.10

add_note(note)

>>> try:
... raise TypeError('bad type')
... except Exception as e:
... e.add_note('Add some information')
... e.add_note('Add some more information')
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
raise TypeError('bad type')
TypeError: bad type
Add some information
Add some more information
>>>

>>> def f():


... raise OSError('operation failed')
...
>>> excs = []
>>> for i in range(3):
... try:
... f()
... except Exception as e:
... e.add_note(f'Happened in Iteration {i+1}')
... [Link](e)
...
>>> raise ExceptionGroup('We have some problems', excs)
+ Exception Group Traceback (most recent call last):
( )

8.10. 65
Python Tutorial, 3.14.0rc3

( )
| File "<stdin>", line 1, in <module>
| raise ExceptionGroup('We have some problems', excs)
| ExceptionGroup: We have some problems (3 sub-exceptions)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| f()
| ~^^
| File "<stdin>", line 2, in f
| raise OSError('operation failed')
| OSError: operation failed
| Happened in Iteration 1
+---------------- 2 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| f()
| ~^^
| File "<stdin>", line 2, in f
| raise OSError('operation failed')
| OSError: operation failed
| Happened in Iteration 2
+---------------- 3 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in <module>
| f()
| ~^^
| File "<stdin>", line 2, in f
| raise OSError('operation failed')
| OSError: operation failed
| Happened in Iteration 3
+------------------------------------
>>>

66 Chapter 8.
CHAPTER 9

Python Python C++ Modula-


3 OOP

Python
C++ public
virtual Modula-3
Smalltalk
Python C++ Modula-3 Python
C++

Smalltalk C++ Modula-3


Modula-3 C++ Python

9.1

Python
Python

Pascal

9.2 Python
Python
Python

namespace Python

abs()

67
Python Tutorial, 3.14.0rc3

maximize

[Link] real z
[Link] modname funcname
1

modname.the_answer = 42 del del modname.the_answer


modname the_answer

Python

__main__
builtins

Python

3 4



nonlocal
nonlocal

Python

Python global nonlocal


del x
x import

global nonlocal

9.2.1
global nonlocal

1 __dict__ __dict__

68 Chapter 9.
Python Tutorial, 3.14.0rc3

def scope_test():
def do_local():
spam = "local spam"

def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"

def do_global():
global spam
spam = "global spam"

spam = "test spam"


do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

After local assignment: test spam


After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

scope_test spam nonlocal scope_test


spam global

global spam

9.3

9.3.1

class ClassName:
< -1>
.
.
.
< -N>

(def ) if

---
---

( )
( )
( ClassName)

9.3. 69
Python Tutorial, 3.14.0rc3

9.3.2 Class

Python : [Link]
:

class MyClass:
""" """
i = 12345

def f(self):
return 'hello world'

MyClass.i MyClass.f
MyClass.i __doc__
: "A simple example class"

x = MyClass()

( )
__init__() :

def __init__(self):
[Link] = []

__init__() __init__()
:

x = MyClass()

__init__()
__init__()

>>> class Complex:


... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

9.3.3

Smalltalk ” ” C++ ” ”
x MyClass
16 :

[Link] = 1
while [Link] < 10:
[Link] = [Link] * 2
print([Link])
del [Link]

70 Chapter 9.
Python Tutorial, 3.14.0rc3

x.f MyClass.f x.i


MyClass.i x.f MyClass.f ---

9.3.4
:

x.f()

x = MyClass() 'hello world'


: x.f :

xf = x.f
while True:
print(xf())

hello world

f()
x.f()
Python --- ...

x.f() MyClass.f(x) n

9.3.5
:

class Dog:

kind = 'canine' #

def __init__(self, name):


[Link] = name #

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> [Link] # Dog
'canine'
>>> [Link] # Dog
'canine'
>>> [Link] # d
'Fido'
>>> [Link] # e
'Buddy'

mutable
tricks Dog
:

9.3. 71
Python Tutorial, 3.14.0rc3

class Dog:

tricks = [] #

def __init__(self, name):


[Link] = name

def add_trick(self, trick):


[Link](trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> [Link] # Dog
['roll over', 'play dead']

class Dog:

def __init__(self, name):


[Link] = name
[Link] = [] # Dog

def add_trick(self, trick):


[Link](trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> [Link]
['roll over']
>>> [Link]
['play dead']

9.4
:

>>> class Warehouse:


... purpose = 'storage'
... region = 'west'
...
>>> w1 = Warehouse()
>>> print([Link], [Link])
storage west
>>> w2 = Warehouse()
>>> [Link] = 'east'
>>> print([Link], [Link])
storage east

Python ---
C Python
C Python
---

---

72 Chapter 9.
Python Tutorial, 3.14.0rc3

self : self Python


Python

#
def f1(self, x, y):
return min(x, x+y)

class C:
f = f1

def g(self):
return 'hello world'

h = g

f g h C C --- h g

self :

class Bag:
def __init__(self):
[Link] = []

def add(self, x):


[Link](x)

def addtwice(self, x):


[Link](x)
[Link](x)

object.__class__

9.5
:

class DerivedClassName(BaseClassName):
< -1>
.
.
.
< -N>

BaseClassName
:

class DerivedClassName([Link]):

9.5. 73
Python Tutorial, 3.14.0rc3

: DerivedClassName()

C++ Python virtual

[Link](self, arguments)
BaseClassName

Python
• isinstance() : isinstance(obj, int) obj.__class__
int int True

• issubclass() : issubclass(bool, int) True bool int


issubclass(float, int) False float int

9.5.1
Python :

class DerivedClassName(Base1, Base2, Base3):


< -1>
.
.
.
< -N>

DerivedClassName
Base1 Base1
Base2

super()
super

object
object

python_2.3_mro

9.6
Python Python
( _spam) API (
)

__spam
_classname__spam classname

74 Chapter 9.
Python Tutorial, 3.14.0rc3

:
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)

def update(self, iterable):


for item in iterable:
self.items_list.append(item)

__update = update # update()

class MappingSubclass(Mapping):

def update(self, keys, values):


# update()
# __init__()
for item in zip(keys, values):
self.items_list.append(item)

MappingSubclass __update
Mapping _Mapping__update MappingSubclass
_MappingSubclass__update

exec() eval() global


getattr(), setattr()
delattr() __dict__

9.7
Pascal ”record” C ”struct”
dataclasses:

from dataclasses import dataclass

@dataclass
class Employee:
name: str
dept: str
salary: int

>>> john = Employee('john', 'computer lab', 1000)


>>> [Link]
'computer lab'
>>> [Link]
1000

Python
read()
readline()

: m.__self__ m() m.__func__

9.7. 75
Python Tutorial, 3.14.0rc3

9.8
for :

for element in [1, 2, 3]:


print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("[Link]"):
print(line, end='')

Python
for iter() __next__()
__next__() StopIteration for
next() __next__() :

>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
next(it)
StopIteration

__iter__()
__next__() __next__() __iter__()
self:

class Reverse:
""" """
def __init__(self, data):
[Link] = data
[Link] = len(data)

def __iter__(self):
return self

def __next__(self):
if [Link] == 0:
raise StopIteration
[Link] = [Link] - 1
return [Link][[Link]]

>>> rev = Reverse('spam')


>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
... print(char)
...
( )

76 Chapter 9.
Python Tutorial, 3.14.0rc3

( )
m
a
p
s

9.9

yield next()
:

def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]

>>> for char in reverse('golf'):


... print(char)
...
f
l
o
g

__iter__() __next__()

self.
index [Link]

StopIteration

9.10

>>> sum(i*i for i in range(10)) #


285

>>> xvec = [10, 20, 30]


>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec)) #
260

>>> unique_words = set(word for line in page for word in [Link]())

>>> valedictorian = max(([Link], [Link]) for student in graduates)

>>> data = 'golf'


>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']

9.9. 77
Python Tutorial, 3.14.0rc3

78 Chapter 9.
CHAPTER 10

10.1
os :

>>> import os
>>> [Link]() #
'C:\\Python314'
>>> [Link]('/server/accesslogs') #
>>> [Link]('mkdir today') # shell mkdir
0

import os from os import * open() [Link]()

dir() help() os:

>>> import os
>>> dir(os)
< >
>>> help(os)
< >

shutil :

>>> import shutil


>>> [Link]('[Link]', '[Link]')
'[Link]'
>>> [Link]('/build/executables', 'installdir')
'installdir'

10.2
glob :

>>> import glob


>>> [Link]('*.py')
['[Link]', '[Link]', '[Link]']

79
Python Tutorial, 3.14.0rc3

10.3
sys argv
[Link] :

# [Link]
import sys
print([Link])

python [Link] one two three :

['[Link]', 'one', 'two', 'three']

argparse
:

import argparse

parser = [Link](
prog='top',
description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)

python [Link] --lines=5 [Link] [Link] [Link]


5 [Link] ['[Link]', '[Link]']

10.4
sys stdin stdout stderr stdout
:

>>> [Link]('Warning, log file not found starting a new one\n')


Warning, log file not found starting a new one

[Link]()

10.5
re
:

>>> import re
>>> [Link](r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> [Link](r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

>>> 'tea for too'.replace('too', 'two')


'tea for two'

80 Chapter 10.
Python Tutorial, 3.14.0rc3

10.6
math C :

>>> import math


>>> [Link]([Link] / 4)
0.70710678118654757
>>> [Link](1024, 2)
10.0

random :

>>> import random


>>> [Link](['apple', 'pear', 'banana'])
'apple'
>>> [Link](range(100), 10) #
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> [Link]() # [0.0, 1.0)
0.17970987693706186
>>> [Link](6) # range(6)
4

statistics :

>>> import statistics


>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> [Link](data)
1.6071428571428572
>>> [Link](data)
1.25
>>> [Link](data)
1.3720238095238095

SciPy <[Link]

10.7
[Link] URL
smtplib :

>>> from [Link] import urlopen


>>> with urlopen('[Link] as response:
... for line in response:
... line = [Link]() #
... if [Link]('datetime'):
... print([Link]()) #
...
datetime: 2022-01-01T01:36:47.689215+00:00

>>> import smtplib


>>> server = [Link]('localhost')
>>> [Link]('soothsayer@[Link]', 'jcaesar@[Link]',
... """To: jcaesar@[Link]
... From: soothsayer@[Link]
...
... Beware the Ides of March.
... """)
>>> [Link]()

localhost

10.6. 81
Python Tutorial, 3.14.0rc3

10.8
datetime

>>> #
>>> from datetime import date
>>> now = [Link]()
>>> now
[Link](2003, 12, 2)
>>> [Link]("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> #
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> [Link]
14368

10.9
zlib, gzip, bz2, lzma, zipfile tarfile :
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = [Link](s)
>>> len(t)
37
>>> [Link](t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

10.10
Python Python

timeit
:
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

timeit profile pstats

10.11

doctest

doctest :

82 Chapter 10.
Python Tutorial, 3.14.0rc3

def average(values):
"""

>>> print(average([20, 30, 70]))


40.0
"""
return sum(values) / len(values)

import doctest
[Link]() #

unittest doctest :

import unittest

class TestStatisticalFunctions([Link]):

def test_average(self):
[Link](average([20, 30, 70]), 40.0)
[Link](round(average([1, 5, 7]), 1), 4.3)
with [Link](ZeroDivisionError):
average([])
with [Link](TypeError):
average(20, 30, 70)

[Link]() #

10.12
Python :
• [Link] [Link]
XML
• email MIME RFC 2822
smtplib poplib

• json csv
XML [Link]
[Link] [Link] Python

• sqlite3 SQLite SQL

• gettext locale codecs

10.12. 83
Python Tutorial, 3.14.0rc3

84 Chapter 10.
CHAPTER 11

11.1
reprlib repr() :

>>> import reprlib


>>> [Link](set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

pprint
:

>>> import pprint


>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> [Link](t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]

textwrap :

>>> import textwrap


>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print([Link](doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

85
Python Tutorial, 3.14.0rc3

locale locale format grouping


:

>>> import locale


>>> [Link](locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = [Link]() #
>>> x = 1234567.8
>>> locale.format_string("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'

11.2
string Template

$ Python

$$ $:

>>> from string import Template


>>> t = Template('${village}folk send $$10 to $cause.')
>>> [Link](village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'

substitute() KeyError
safe_substitute()

>>> t = Template('Return the $item to $owner.')


>>> d = dict(item='unladen swallow')
>>> [Link](d)
Traceback (most recent call last):
...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'

Template
:

>>> import time, [Link]


>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
...
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f

>>> t = BatchRename(fmt)
>>> date = [Link]('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = [Link](filename)
... newname = [Link](d=date, n=i, f=ext)
... print('{0} --> {1}'.format(filename, newname))

img_1074.jpg --> Ashley_0.jpg


( )

86 Chapter 11.
Python Tutorial, 3.14.0rc3

( )
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg

XML
HTML

11.3
struct pack() unpack()
zipfile ZIP Pack "H" "I"
"<" :
import struct

with open('[Link]', 'rb') as f:


data = [Link]()

start = 0
for i in range(3): # 3
start += 14
fields = [Link]('<IIIHH', data[start:start+16])
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print(filename, hex(crc32), comp_size, uncomp_size)

start += extra_size + comp_size #

11.4

I/O

threading :
import threading, zipfile

class AsyncZip([Link]):
def __init__(self, infile, outfile):
[Link].__init__(self)
[Link] = infile
[Link] = outfile

def run(self):
f = [Link]([Link], 'w', zipfile.ZIP_DEFLATED)
[Link]([Link])
[Link]()
print('Finished background zip of:', [Link])

background = AsyncZip('[Link]', '[Link]')


[Link]()
print('The main program continues to run in foreground.')

[Link]() #
print('Main program waited until background was done.')

11.3. 87
Python Tutorial, 3.14.0rc3

threading

queue
Queue

11.5
logging
[Link]

import logging
[Link]('Debugging information')
[Link]('Informational message')
[Link]('Warning:config file %s not found', '[Link]')
[Link]('Error occurred')
[Link]('Critical error -- shutting down')

WARNING:root:Warning:config file [Link] not found


ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down

informational debugging
HTTP
DEBUG INFO WARNING ERROR CRITICAL

Python

11.6
Python garbage collection

weakref

>>> import weakref, gc


>>> class A:
... def __init__(self, value):
... [Link] = value
... def __repr__(self):
... return str([Link])
...
>>> a = A(10) # create a reference
>>> d = [Link]()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
>>> del a # remove the one reference
>>> [Link]() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
( )

88 Chapter 11.
Python Tutorial, 3.14.0rc3

( )
d['primary'] # entry was automatically removed
File "C:/python314/lib/[Link]", line 46, in __getitem__
o = [Link][key]()
KeyError: 'primary'

11.7

array array
( "H") Python int
16 :

>>> from array import array


>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])

collections deque
:

>>> from collections import deque


>>> d = deque(["task1", "task2", "task3"])
>>> [Link]("task4")
>>> print("Handling", [Link]())
Handling task1

unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = [Link]()
for m in gen_moves(node):
if is_goal(m):
return m
[Link](m)

bisect :

>>> import bisect


>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> [Link](scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

heapq
:

>>> from heapq import heapify, heappop, heappush


>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) #
>>> heappush(data, -5) #
>>> [heappop(data) for i in range(3)] #
[-5, 0, 1]

11.7. 89
Python Tutorial, 3.14.0rc3

11.8
decimal Decimal float






70 5
:

>>> from decimal import *


>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73

Decimal Decimal

Decimal :

>>> Decimal('1.00') % Decimal('.10')


Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')


True
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False

decimal :

>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')

90 Chapter 11.
CHAPTER 12

12.1
Python

Python A 1.0
B 2.0 1.0 2.0
virtual environment Python

A
1.0 B 2.0
B 3.0 A

12.2
venv venv Python --version
python3.12 3.12
venv :

python -m venv tutorial-env

tutorial-env Python

.venv
.env

Windows :

tutorial-env\Scripts\activate

Unix MacOS :

91
Python Tutorial, 3.14.0rc3

source tutorial-env/bin/activate

bash shell csh fish shell [Link] activate.


fish

python
Python

$ source ~/envs/tutorial-env/bin/activate
(tutorial-env) $ python
Python 3.5.1 (default, May 6 2016, 10:59:36)
...
>>> import sys
>>> [Link]
['', '/usr/local/lib/[Link]', ...,
'~/envs/tutorial-env/lib/python3.5/site-packages']
>>>

deactivate

12.3 pip
pip pip Python Package Index
web Python Package Index
pip : ”install”, ”uninstall”, ”freeze” installing-index pip

(tutorial-env) $ python -m pip install novas


Collecting novas
Downloading [Link] (136kB)
Installing collected packages: novas
Running [Link] install for novas
Successfully installed novas-[Link]

==

(tutorial-env) $ python -m pip install requests==2.6.0


Collecting requests==2.6.0
Using cached [Link]
Installing collected packages: requests
Successfully installed requests-2.6.0

pip
python -m pip install --upgrade
:

(tutorial-env) $ python -m pip install --upgrade requests


Collecting requests
Installing collected packages: requests
Found existing installation: requests 2.6.0
Uninstalling requests-2.6.0:
Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0

python -m pip uninstall

92 Chapter 12.
Python Tutorial, 3.14.0rc3

python -m pip show :

(tutorial-env) $ python -m pip show requests


---
Metadata-Version: 2.0
Name: requests
Version: 2.7.0
Summary: Python HTTP for Humans.
Home-page: [Link]
Author: Kenneth Reitz
Author-email: me@[Link]
License: Apache 2.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:

python -m pip list :

(tutorial-env) $ python -m pip list


novas ([Link])
numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (16.0)

python -m pip freeze python -m pip install


[Link] :

(tutorial-env) $ python -m pip freeze > [Link]


(tutorial-env) $ cat [Link]
novas==[Link]
numpy==1.9.2
requests==2.7.0

[Link]
install -r

(tutorial-env) $ python -m pip install -r [Link]


Collecting novas==[Link] (from -r [Link] (line 1))
...
Collecting numpy==1.9.2 (from -r [Link] (line 2))
...
Collecting requests==2.7.0 (from -r [Link] (line 3))
...
Installing collected packages: novas, numpy, requests
Running [Link] install for novas
Successfully installed novas-[Link] numpy-1.9.2 requests-2.7.0

pip pip installing-index


Python Package Index Python packaging user guide

12.3. pip 93
Python Tutorial, 3.14.0rc3

94 Chapter 12.
CHAPTER 13

Python - Python

Python
• library-index:

Python Unix HTTP

• installing-index Python
• reference-index: Python

Python
• [Link] Python Python
• [Link] Python
• [Link] The Python Package Index Cheese Shop1 Python

• [Link] Python Cookbook


Python Cookbook O’Reilly Associates
ISBN 0-596-00797-3
• [Link] Python
• [Link] Scientific Python

Python [Link]
python-list@[Link]

[Link]
FAQ

1 Cheese Shop Monty Python

95
Python Tutorial, 3.14.0rc3

96 Chapter 13.
CHAPTER 14

Python Korn shell GNU Bash shell


GNU Readline

14.1 Tab
Tab
Python string.a
'.' __getattr__()

.python_history

14.2

INDENT

IPython tab

bpython

97
Python Tutorial, 3.14.0rc3

98 Chapter 14.
CHAPTER 15

2( ) 0.625 6/10 +
2/100 + 5/1000 0.101 1/2 + 0/4 + 1/8
10 2

1/3

0.3

0.33

0.333

1/3 1/3
2 0.1 2
2 1/10

0.0001100110011001100110011001100110011001100110011...

8 53 2 1/10
3602879701896397 / 2 ** 55 1/10 1/10
Python
Python 0.1
:

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625

Python :

99
Python Tutorial, 3.14.0rc3

>>> 1 / 10
0.1

1/10 1/10

0.1 0.
10000000000000001 0.1000000000000000055511151231257827021181583404541015625
3602879701896397 / 2 ** 55
eval(repr(x)) == x
Python repr() 17 0.
10000000000000001 Python 3.1 Python
0.1
Python

>>> format([Link], '.12g') # 12


'3.14159265359'

>>> format([Link], '.2f') # 2


'3.14'

>>> repr([Link])
'3.141592653589793'

0.1 1/10 0.1


0.3:

>>> 0.1 + 0.1 + 0.1 == 0.3


False

0.1 1/10 0.3 3/10 round()


:

>>> round(0.1, 1) + round(0.1, 1) + round(0.1, 1) == round(0.3, 1)


False

[Link]()
:

>>> [Link](0.1 + 0.1 + 0.1, 0.3)


True

round()

>>> round([Link], ndigits=2) == round(22 / 7, ndigits=2)


True

”0.1” ” ”
Examples of Floating Point Problems
The Perils of Floating Point
Python
2**53
1

100 Chapter 15.


Python Tutorial, 3.14.0rc3

str()
formatstrings [Link]()

decimal

fractions
1/3
NumPy SciPy
<[Link]
Python
float.as_integer_ratio() :

>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

>>> x == 3537115888337719 / 1125899906842624


True

[Link]() 16
:

>>> [Link]()
'0x1.921f9f01b866ep+1'

>>> x == [Link]('0x1.921f9f01b866ep+1')
True

Python
Java C99 .
sum()

>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False
>>> sum([0.1] * 10) == 1.0
True

[Link]() sum()

>>> arr = [-0.10430216751806065, -266310978.67179024, 143401161448607.16,


... -143401161400469.7, 266262841.31058735, -0.003244936839808227]
>>> float(sum(map(Fraction, arr))) #
8.042173697819788e-13
>>> [Link](arr) #
8.042173697819788e-13
>>> sum(arr) #
8.042178034628478e-13
>>> total = 0.0
>>> for x in arr:
... total += x #
( )

101
Python Tutorial, 3.14.0rc3

( )
...
>>> total #
-0.0051575902860057365

15.1
”0.1”

2
Python Perl C C++ Java Fortran

1/10 2000 IEEE 754


Python IEEE 754 binary64 ” ”
IEEE 754 binary64 53 0.1 J/2**N
J 53

1 / 10 ~= J / (2**N)

J ~= 2**N / 10

J 53 ( >= 2**52 < 2**53) N 56:

>>> 2**52 <= 2**56 // 10 < 2**53


True

56 J 53 N J :

>>> q, r = divmod(2**56, 10)


>>> r
6

10 :

>>> q+1
7205759403792794

IEEE 754 1/10 :

7205759403792794 / 2 ** 56

3602879701896397 / 2 ** 55

1/10
1/10 1/10
” ” 1/10: IEEE 754
:

>>> 0.1 * 2 ** 55
3602879701896397.0

10**55 55 :

102 Chapter 15.


Python Tutorial, 3.14.0rc3

>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625

0.1000000000000000055511151231257827021181583404541015625
Python 17
:

>>> format(0.1, '.17f')


'0.10000000000000001'

fractions decimal :

>>> from decimal import Decimal


>>> from fractions import Fraction

>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

>>> format(Decimal.from_float(0.1), '.17')


'0.10000000000000001'

15.1. 103
Python Tutorial, 3.14.0rc3

104 Chapter 15.


CHAPTER 16

16.1
REPL
Windows curses Unix Python 3.13
shell using-on-controlling-color
F1 pydoc F2 »>
... F3 F3

shell exit quit shell

shell PYTHON_BASIC_REPL

16.1.1

try except

1
Control-C Delete
KeyboardInterrupt try

16.1.2 Python
BSD Unix Python shell

#!/usr/bin/env python3

PATH #!
Unix '\n' Windows '\r\n'
'#' Python
chmod
1 GNU Readline

105
Python Tutorial, 3.14.0rc3

$ chmod +x [Link]

Windows Python .py [Link]


Python .pyw

16.1.3
Python
PYTHONSTARTUP
Unix shell .profile

Python /dev/tty
Python
sys.ps1
sys.ps2

if
[Link]('.[Link]'): exec(open('.[Link]').read())

import os
filename = [Link]('PYTHONSTARTUP')
if filename and [Link](filename):
with open(filename) as fobj:
startup_file = [Link]()
exec(startup_file)

16.1.4
Python : sitecustomize usercustomize
site-packages Python :

>>> import site


>>> [Link]()
'/home/user/.local/lib/python3.x/site-packages'

[Link]
Python -s

sitecustomize site-packages usercustomize


site

106 Chapter 16.


APPENDIX A

>>>
interactive shell Python

...

• interactive shell Python


abstract base class --
ABC duck-typing
hasattr() ABC
isinstance() issubclass() abc
Python ABC [Link] numbers
io [Link] abc
ABC
annotate function --
__annotate__

annotation --

annotationlib.get_annotations()

variable annotation, function annotation, PEP 484, PEP 526 PEP 649
annotations-howto
argument --
function method
• : name= **
3 5 complex() :

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

107
Python Tutorial, 3.14.0rc3

• : /
* iterable 3 5 :

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
attached thread state --
OS thread state
thread state OS Python C API
C API
C API
C
Python GIL
Python

attribute --
o a
o.a
identifiers
setattr() getattr()

awaitable --
await coroutine __await__()
PEP 492

108 Appendix A.
Python Tutorial, 3.14.0rc3

BDFL
Guido van Rossum Python
binary file --
file object ('rb', 'wb' 'rb+')
[Link] [Link] [Link] [Link]

text file str


borrowed reference --
Python C API
strong reference

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

109
Python Tutorial, 3.14.0rc3

codeobject.co_freevars
free variable

complex number --
-1
i j Python
j 3+1j math
cmath

context --

• with context manager


• [Link] ContextVar
context variable
• [Link] current context
context management protocol --
__enter__() __exit__() with PEP 343
context manager --
context management protocol with PEP 343
context variable --
current context [Link]

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 [Link] ”CPython”
Jython IronPython
current context --
ContextVar ( ) context (contextvars.
Context ) ( asyncio)

cyclic isolate --

decorator --
@wrapper
classmethod() staticmethod()

110 Appendix A.
Python Tutorial, 3.14.0rc3

def f(arg):
...
f = staticmethod(f)

@staticmethod
def f(arg):
...

descriptor --
__get__(), __set__() __delete__()
a.b
a b b
Python

descriptors
dictionary --
__hash__() __eq__()
Perl hash
dictionary comprehension --
results = {n: n **
2 for n in range(10)} n n ** 2 comprehensions
dictionary view --
[Link](), [Link]() [Link]()

list(dictview) dict-views
docstring --

__doc__

duck-typing --

type() isinstance()
( ) hasattr() EAFP

dunder
”double underscore” special method __init__
”dunder init”
EAFP
Python
try except
LBYL C
evaluate function --
type

expression --

statement while

111
Python Tutorial, 3.14.0rc3

extension module --
C C++ Python C API
f-string -- f-
f-strings -- 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

[Link]() [Link]()

filesystem encoding and error handler Python PyConfig_Read()


PyConfig filesystem_encoding filesystem_errors

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

112 Appendix A.
Python Tutorial, 3.14.0rc3

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
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 [Link]() 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

113
Python Tutorial, 3.14.0rc3

Python’s C API GIL


attached thread state
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
sys._is_immortal() C API PyUnstable_IsImmortal()
immutable --

import path --
path based finder
[Link] __path__

importing --
Python Python
importer --
finder loader
interactive --
Python
python
help(x)

interpreted --
Python

/ interactive
interpreter shutdown --
Python

__main__
iterable --
list, str tuple

114 Appendix A.
Python Tutorial, 3.14.0rc3

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 --
[Link]()

Python min(),
max(), sorted(), [Link](), [Link](), [Link](), [Link]()
[Link]()

[Link]()
lambda lambda r: (r[0], r[2]) operator.
attrgetter(), [Link]() [Link]()

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)

115
Python Tutorial, 3.14.0rc3

loader --
exec_module() create_module() Loader
finder
• finders-and-loaders
• [Link]
• PEP 302
locale encoding --
Unix LC_CTYPE [Link](locale.
LC_CTYPE, new_locale)

Windows ANSI ( : "cp1252")


Android VxWorks Python "utf-8"

[Link]()
filesystem encoding and error handler
magic method --
special method
mapping --
[Link] [Link].
MutableMapping dict, collections.
defaultdict, [Link] [Link]
meta path finder --
sys.meta_path finder path entry finders
[Link]

metaclass --

Python

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 --
[Link]

module-specs
MRO
method resolution order
mutable --
id() immutable

116 Appendix A.
Python Tutorial, 3.14.0rc3

named tuple --

[Link]() [Link]()
sys.float_info:

>>> sys.float_info[1] #
1024
>>> sys.float_info.max_exp #
1024
>>> isinstance(sys.float_info, tuple) #
True

tuple
typing.
NamedTuple [Link]()

namespace --

[Link] [Link]()

[Link]() [Link]() random


itertools

namespace package --
package regular
package __init__.py

regular package
PEP 420 reference-namespace-package
module
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

117
Python Tutorial, 3.14.0rc3

• 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 [Link] function


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

[Link]
path entry hook --
path entry sys.path_hooks
path entry finder
path based finder --
import path
path-like object --
str bytes
[Link] [Link] os.
fspath() str bytes [Link]() [Link]()
str bytes PEP 519
PEP
Python PEP Python
Python PEP

PEP Python
PEP
PEP 1
portion --
zip PEP
420

118 Appendix A.
Python Tutorial, 3.14.0rc3

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)

qualified name --

PEP 3155 :

>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> [Link].__qualname__
'[Link]'

[Link]:

>>> import [Link]


>>> [Link].__name__
'[Link]'

reference count --
immortal
Python
CPython [Link]()

119
Python Tutorial, 3.14.0rc3

CPython Python

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
[Link] __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

soft deprecated --
API API

API
PEP 387: Soft Deprecation
special method --
Python
specialnames
standard library --
Python ,
library-index

sys.stdlib_module_names

statement --
expression
if while for

static type checker --


Python
typing

120 Appendix A.
Python Tutorial, 3.14.0rc3

stdlib --
standard library
strong reference --
Python C API
Py_INCREF() Py_DECREF()

Py_NewRef()
Py_DECREF()

borrowed reference
t-string -- t-
t-strings -- t-
t T ”t- ”
text encoding --
Python Unicode U+0000--U+10FFFF

” ”
text file --
str file object
text encoding 'r' 'w' [Link]
[Link] [Link]

binary file
thread state --
CPython OS

OS

Python C API attached thread state

OS

token --
( )

tokenize Python token

triple-quoted string --
” ’

type --
Python
__class__ type(obj)

type alias --

121
Python Tutorial, 3.14.0rc3

def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass

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”

122 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

123
Python Tutorial, 3.14.0rc3

124 Appendix B.
APPENDIX C

C.1
Python 1990 Guido van Rossum Stichting Mathematisch Centrum (CWI https:
//[Link]) ABC Guido Python

1995 Guido Reston Corporation for National Research Initiatives (CNRI https:
//[Link]) Python
2000 5 Guido Python [Link] BeOpen PythonLabs
10 PythonLabs Digital Creations Zope Corporation 2001 Python Software
Foundation (PSF [Link] Python
Zope Corporation PSF
Python ( [Link]
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 [Link]
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

125
Python Tutorial, 3.14.0rc3

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

126 Appendix C.
Python Tutorial, 3.14.0rc3

C.2.2 PYTHON 2.0 [Link]


BEOPEN PYTHON 1
1. This LICENSE AGREEMENT is between [Link] ("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
[Link] 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 127


Python Tutorial, 3.14.0rc3

( )
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: [Link]

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

128 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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 [Link]
MT2002/[Link] :
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. 129
Python Tutorial, 3.14.0rc3

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


[Link]
email: m-mat @ [Link] (remove space)

C.3.2
socket getaddrinfo() getnameinfo() WIDE : [Link]
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
[Link] [Link] :
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
( )

130 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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
[Link] :

Copyright 2000 by Timothy O'Malley <timo@[Link]>

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
[Link]
[Link]

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. 131
Python Tutorial, 3.14.0rc3

( )
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
[Link] :

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

132 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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. 133
Python Tutorial, 3.14.0rc3

C.3.10 SipHash24
Python/pyhash.c Marek Majkowski’ Dan Bernstein SipHash24
:
<MIT License>
Copyright (c) 2013 Marek Majkowski <marek@[Link]>

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:
[Link]

Solution inspired by code from:


Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson ([Link]

C.3.11 strtod dtoa


Python/dtoa.c C dtoa strtod C
David M. Gay [Link]
//[Link]/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
[Link]
( )

134 Appendix C.
Python Tutorial, 3.14.0rc3

( )

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. 135
Python Tutorial, 3.14.0rc3

( )

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

136 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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. 137
Python Tutorial, 3.14.0rc3

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

138 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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@[Link] madler@[Link]

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. 139
Python Tutorial, 3.14.0rc3

( )

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 [Link]
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


( )

140 Appendix C.
Python Tutorial, 3.14.0rc3

( )
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. [Link]

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@[Link]>

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. 141
Python Tutorial, 3.14.0rc3

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

C.3.22 Zstandard
Modules/_zstd Lib/compression/zstd Zstandard pyzstd
Ma Lin pyzstd 3 BSD :

Copyright (c) 2020-present, Ma Lin and contributors.


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 copyright holder 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 HOLDER 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.

142 Appendix C.
APPENDIX D

Python
© 2001 Python
© 2000 [Link]
© 1995-2000 Corporation for National Research Initiatives
© 1991-1995 Stichting Mathematisch Centrum

143
Python Tutorial, 3.14.0rc3

144 Appendix D.
asynchronous iterable -- ,
..., 107 108
ellipsis literal -- , 107 asynchronous iterator -- , 108
, 18 attached thread state -- , 108
# (hash) attribute -- , 108
,7 awaitable -- , 108
*( )
, 27 B
** BDFL, 109
, 27 binary file -- , 109
:( ) borrowed reference -- , 109
, 28 builtins
-> module, 45
, 28 bytecode -- , 109
>>>, 107 bytes-like object -- , 109
__all__, 47
__future__, 113 C
__slots__, 120 C , 110
callable -- , 109
method -- , 120 callback -- , 109
class -- , 109
PATH, 43, 105 class variable -- , 109
PYTHON_BASIC_REPL, 105 closure variable -- , 109
PYTHON_GIL, 113 complex number -- , 110
PYTHONPATH, 43, 44 context -- , 110
PYTHONSTARTUP, 106 context management protocol --
, 110
style, 28 context manager -- , 110
context variable -- , 110
method -- , 116 contiguous -- , 110
coroutine -- , 110
A coroutine function -- , 110
abstract base class -- , 107 CPython, 110
annotate function -- , 107 current context -- , 110
annotation -- , 107 cyclic isolate -- , 110
annotations
function -- , 28 D
argument -- , 107 decorator -- , 110
asynchronous context manager -- descriptor -- , 111
, 108 dictionary -- , 111
asynchronous generator -- , 108 dictionary comprehension -- , 111
asynchronous generator iterator -- dictionary view -- , 111
, 108 docstring -- , 111

145
Python Tutorial, 3.14.0rc3

duck-typing -- , 111 interpreter shutdown -- , 114


dunder, 111 iterable -- , 114
iterator -- , 115
E
EAFP, 111 J
evaluate function -- , 111 json
expression -- , 111 module, 55
extension module -- , 112
K
F key function -- , 115
f-string -- f- , 112 keyword argument -- , 115
f-strings -- f- , 112
file object -- , 112 L
file-like object -- , 112 lambda, 115
filesystem encoding and error handler -- LBYL, 115
, 112 lexical analyzer -- , 115
finder -- , 112 list -- , 115
floor division -- , 112 list comprehension -- , 115
for loader -- , 116
statement -- , 15 locale encoding -- , 116
Fortran , 110
free threading -- , 112 M
free variable -- , 112 magic method -- , 116
fstring, 50
mapping -- , 116
f-string -- f- , 50 meta path finder -- , 116
function --
metaclass -- , 116
annotations, 28
method --
function -- , 112 object -- , 71
function annotation -- , 112 , 120
, 116
G method -- , 116
garbage collection -- , 113 method resolution order -- ,
generator -- , 113 116
generator -- , 113 module
generator expression -- , 113 builtins, 45
generator expression -- , 113 json, 55
generator iterator -- , 113 sys, 44
generic function -- , 113 path, 43
generic type -- , 113 module -- , 116
GIL, 113 module spec -- , 116
global interpreter lock -- , MRO, 116
113 mutable -- , 116
H N
hash-based pyc -- pyc, 114 name
hashable -- , 114 , 74
help named tuple -- , 117
, 79 namespace -- , 117
namespace package -- , 117
I nested scope -- , 117
IDLE, 114 new-style class -- , 117
immortal -- , 114
immutable -- , 114 O
import path -- , 114 object --
importer -- , 114 method -- , 71
importing -- , 114 , 53
interactive -- , 114 object -- , 117
interpreted -- , 114

146
Python Tutorial, 3.14.0rc3

open R
, 53 reference count -- , 119
optimized scope -- , 117 regular package -- , 120
REPL, 120
P RFC
package -- , 117 RFC 2822, 83
parameter -- , 117
PATH, 43, 105 S
path sequence -- , 120
module , 43 set comprehension -- , 120
path based finder -- , 118 single dispatch -- , 120
path entry -- , 118 sitecustomize, 106
path entry finder -- , 118 slice -- , 120
path entry hook -- , 118 soft deprecated -- , 120
path-like object -- , 118 special method -- , 120
PEP, 118 standard library -- , 120
portion -- , 118 statement --
positional argument -- , 119 for, 15
provisional API -- API, 119 statement -- , 120
provisional package -- , 119 static type checker -- , 120
Python 3000, 119 stdlib -- , 121
Python PEP 1, 118 string
Python PEP 8, 29 , 50
Python PEP 238, 112 , 50
Python PEP 278, 122 strong reference -- , 121
Python PEP 302, 116 style
Python PEP 343, 110 , 28
Python PEP 362, 108, 118 sys
Python PEP 411, 119 module, 44
Python PEP 420, 117, 118
Python PEP 443, 113 T
Python PEP 483, 113 t-string -- t- , 121
Python PEP 484, 28, 107, 113, 122 t-strings -- t- , 121
Python PEP 492, 108, 110 text encoding -- , 121
Python PEP 498, 112 text file -- , 121
Python PEP 519, 118 thread state -- , 121
Python PEP 525, 108 token -- , 121
Python PEP 526, 107, 122 triple-quoted string -- , 121
Python PEP 585, 113 type -- , 121
Python PEP 636, 21 type alias -- , 121
Python PEP 649, 107 type hint -- , 122
Python PEP 683, 114
Python PEP 703, 112, 113 U
Python PEP 765, 62
universal newlines -- , 122
Python PEP 3107, 28
usercustomize, 106
Python PEP 3116, 122
Python PEP 3147, 44 V
Python PEP 3155, 119
variable annotation -- , 122
PYTHON_BASIC_REPL, 105
PYTHON_GIL, 113
help, 79
Pythonic, 119
open, 53
PYTHONPATH, 43, 44
virtual environment -- , 122
PYTHONSTARTUP, 106
virtual machine -- , 122
Q , 21, 28
qualified name -- , 119 W

147
Python Tutorial, 3.14.0rc3

name, 74
, 50

path, module, 43

object -- , 53
, 21, 28
, 50
, 122

Z
Zen of Python -- Python , 122

148

You might also like