Using
Using
Release 3.12.9
3 Configure Python 21
3.1 Build Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Generated files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2.1 configure script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3 Configure Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.1 General Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.2 WebAssembly Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.3 Install Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3.4 Performance options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3.5 Python Debug Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3.6 Debug options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3.7 Linker options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3.8 Libraries options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3.9 Security Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.3.10 macOS Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.3.11 Cross Compiling Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.4 Python Build System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4.1 Main files of the build system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4.2 Main build steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4.3 Main Makefile targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4.4 C extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.5 Compiler and linker flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5.1 Preprocessor flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5.2 Compiler flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.5.3 Linker flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
i
4 Using Python on Windows 35
4.1 The full installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.1.1 Installation steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.1.2 Removing the MAX_PATH Limitation . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.1.3 Installing Without UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.1.4 Installing Without Downloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.1.5 Modifying an install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 The Microsoft Store package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.2.1 Known issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.3 The nuget.org packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4 The embeddable package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4.1 Python Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4.2 Embedding Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.5 Alternative bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.6 Configuring Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.6.1 Excursus: Setting environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.6.2 Finding the Python executable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.7 UTF-8 mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.8 Python Launcher for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.8.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.8.2 Shebang Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.8.3 Arguments in shebang lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.8.4 Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.8.5 Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.8.6 Dry Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.8.7 Install on demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.8.8 Return codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.9 Finding modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.10 Additional modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.10.1 PyWin32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.10.2 cx_Freeze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.11 Compiling Python on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.12 Other Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
A Glossary 59
ii
C.2.3 CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 . . . . . . . . . . . . . . . . . . 79
C.2.4 CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 . . . . . . . . . . 80
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION . 81
C.3 Licenses and Acknowledgements for Incorporated Software . . . . . . . . . . . . . . . . . . . . . 81
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
C.3.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
C.3.3 Asynchronous socket services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
C.3.4 Cookie management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
C.3.5 Execution tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
C.3.6 UUencode and UUdecode functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
C.3.7 XML Remote Procedure Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
C.3.9 Select kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
C.3.11 strtod and dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
C.3.18 W3C C14N test suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
C.3.19 Audioop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
D Copyright 95
Index 97
iii
iv
Python Setup and Usage, Release 3.12.9
This part of the documentation is devoted to general information on the setup of the Python environment on different
platforms, the invocation of the interpreter and things that make working with Python easier.
CONTENTS 1
Python Setup and Usage, Release 3.12.9
2 CONTENTS
CHAPTER
ONE
The CPython interpreter scans the command line and the environment for various settings.
CPython implementation detail: Other implementations’ command line schemes may differ. See implementations
for further resources.
The most common use case is, of course, a simple invocation of a script:
python myscript.py
-c <command>
Execute the Python code in command. command can be one or more statements separated by newlines, with
significant leading whitespace as in normal module code.
If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to
the start of sys.path (allowing modules in that directory to be imported as top level modules).
Raises an auditing event cpython.run_command with argument command.
3
Python Setup and Usage, Release 3.12.9
-m <module-name>
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you must not give a file extension (.py). The module name should be
a valid absolute Python module name, but the implementation may not always enforce this (e.g. it may allow
you to use a name that includes a hyphen).
Package names (including namespace packages) are also permitted. When a package name is supplied instead
of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is
deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script
argument.
® Note
This option cannot be used with built-in modules and extension modules written in C, since they do not
have Python module files. However, it can still be used for precompiled modules, even if the original source
file is not available.
If this option is given, the first element of sys.argv will be the full path to the module file (while the module
file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be
added to the start of sys.path.
-I option can be used to run the script in isolated mode where sys.path contains neither the current directory
nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Many standard library modules contain code that is invoked on their execution as a script. An example is the
timeit module:
µ See also
runpy.run_module()
Equivalent functionality directly available to Python code
Changed in version 3.1: Supply the package name to run a __main__ submodule.
Changed in version 3.4: namespace packages are also supported
-
Read commands from standard input (sys.stdin). If standard input is a terminal, -i is implied.
If this option is given, the first element of sys.argv will be "-" and the current directory will be added to
the start of sys.path.
Raises an auditing event cpython.run_stdin with no arguments.
<script>
Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to
either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.
If this option is given, the first element of sys.argv will be the script name as given on the command line.
If the script name refers directly to a Python file, the directory containing that file is added to the start of
sys.path, and the file is executed as the __main__ module.
If the script name refers to a directory or zipfile, the script name is added to the start of sys.path and the
__main__.py file in that location is executed as the __main__ module.
-I option can be used to run the script in isolated mode where sys.path contains neither the script’s directory
nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Raises an auditing event cpython.run_file with argument filename.
µ See also
runpy.run_path()
Equivalent functionality directly available to Python code
If no interface option is given, -i is implied, sys.argv[0] is an empty string ("") and the current directory will
be added to the start of sys.path. Also, tab-completion and history editing is automatically enabled, if available
on your platform (see rlcompleter-config).
µ See also
tut-invoking
Python 3.8.0b2+
When given twice, print more information about the build, like:
--check-hash-based-pycs default|always|never
Control the validation behavior of hash-based .pyc files. See pyc-invalidation. When set to default, checked
and unchecked hash-based bytecode cache files are validated according to their default semantics. When set to
always, all hash-based .pyc files, whether checked or unchecked, are validated against their corresponding
source file. When set to never, hash-based .pyc files are not validated against their corresponding source
files.
The semantics of timestamp-based .pyc files are unaffected by this option.
-d
Turn on parser debugging output (for expert only). See also the PYTHONDEBUG environment variable.
This option requires a debug build of Python, otherwise it’s ignored.
-E
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.
See also the -P and -I (isolated) options.
-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the
script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file
is not read.
This can be useful to inspect global variables or a stack trace when a script raises an exception. See also
PYTHONINSPECT .
-I
Run Python in isolated mode. This also implies -E, -P and -s options.
In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory. All
PYTHON* environment variables are ignored, too. Further restrictions may be imposed to prevent the user
from injecting malicious code.
Added in version 3.4.
-O
Remove assert statements and any code conditional on the value of __debug__. Augment the filename
for compiled (bytecode) files by adding .opt-1 before the .pyc extension (see PEP 488). See also
PYTHONOPTIMIZE.
• python script.py command line: Don’t prepend the script’s directory. If it’s a symbolic link, resolve
symbolic links.
• python -c code and python (REPL) command lines: Don’t prepend an empty string, which means
the current working directory.
See also the PYTHONSAFEPATH environment variable, and -E and -I (isolated) options.
Added in version 3.11.
-q
Don’t display the copyright and version messages even in interactive mode.
Added in version 3.2.
-R
Turn on hash randomization. This option only has an effect if the PYTHONHASHSEED environment variable is
set to 0, since hash randomization is enabled by default.
On previous versions of Python, this option turns on hash randomization, so that the __hash__() values of
str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within
an individual Python process, they are not predictable between repeated invocations of Python.
Hash randomization is intended to provide protection against a denial-of-service caused by carefully chosen
inputs that exploit the worst case performance of a dict construction, O(n2 ) complexity. See http://ocert.org/
advisories/ocert-2011-003.html for details.
PYTHONHASHSEED allows you to set a fixed value for the hash seed secret.
Added in version 3.2.3.
Changed in version 3.7: The option is no longer ignored.
-s
Don’t add the user site-packages directory to sys.path.
See also PYTHONNOUSERSITE.
µ See also
-S
Disable the import of the module site and the site-dependent manipulations of sys.path that it entails.
Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to
be triggered).
-u
Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
See also PYTHONUNBUFFERED.
Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.
-v
Print a message each time a module is initialized, showing the place (filename or built-in module) from which
it is loaded. When given twice (-vv), print a message for each file that is checked for when searching for a
module. Also provides information on module cleanup at exit.
Changed in version 3.10: The site module reports the site-specific paths and .pth files being processed.
See also PYTHONVERBOSE.
-W arg
Warning control. Python’s warning machinery by default prints warning messages to sys.stderr.
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those
that are otherwise ignored by default):
The action names can be abbreviated as desired and the interpreter will resolve them to the appropriate action
name. For example, -Wi is the same as -Wignore.
The full form of argument is:
action:message:category:module:lineno
Empty fields match all values; trailing empty fields may be omitted. For example -W
ignore::DeprecationWarning ignores all DeprecationWarning warnings.
The action field is as explained above but only applies to warnings that match the remaining fields.
The message field must match the whole warning message; this match is case-insensitive.
The category field matches the warning category (ex: DeprecationWarning). This must be a class name; the
match test whether the actual warning category of the message is a subclass of the specified warning category.
The module field matches the (fully qualified) module name; this match is case-sensitive.
The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an
omitted line number.
Multiple -W options can be given; when a warning matches more than one option, the action for the last
matching option is performed. Invalid -W options are ignored (though, a warning message is printed about
invalid options when the first warning is issued).
Warnings can also be controlled using the PYTHONWARNINGS environment variable and from within a Python
program using the warnings module. For example, the warnings.filterwarnings() function can be
used to use a regular expression on the warning message.
See warning-filter and describing-warning-filters for more details.
-x
Skip the first line of the source, allowing use of non-Unix forms of #!cmd. This is intended for a DOS specific
hack only.
-X
Reserved for various implementation-specific options. CPython currently defines the following possible values:
• -X faulthandler to enable faulthandler. See also PYTHONFAULTHANDLER.
Added in version 3.3.
• -X showrefcount to output the total reference count and number of used memory blocks when the
program finishes or after each statement in the interactive interpreter. This only works on debug builds.
Added in version 3.4.
• -X tracemalloc to start tracing Python memory allocations using the tracemalloc module. By de-
fault, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME
to start tracing with a traceback limit of NFRAME frames. See tracemalloc.start() and
PYTHONTRACEMALLOC for more information.
Raises an auditing event cpython.run_startup with the filename as the argument when called on startup.
PYTHONOPTIMIZE
If this is set to a non-empty string it is equivalent to specifying the -O option. If set to an integer, it is equivalent
to specifying -O multiple times.
PYTHONBREAKPOINT
If this is set, it names a callable using dotted-path notation. The module containing the callable will be im-
ported and then the callable will be run by the default implementation of sys.breakpointhook() which
itself is called by built-in breakpoint(). If not set, or set to the empty string, it is equivalent to the value
“pdb.set_trace”. Setting this to the string “0” causes the default implementation of sys.breakpointhook()
to do nothing but return immediately.
Added in version 3.7.
PYTHONDEBUG
If this is set to a non-empty string it is equivalent to specifying the -d option. If set to an integer, it is equivalent
to specifying -d multiple times.
This environment variable requires a debug build of Python, otherwise it’s ignored.
PYTHONINSPECT
If this is set to a non-empty string it is equivalent to specifying the -i option.
This variable can also be modified by Python code using os.environ to force inspect mode on program
termination.
Raises an auditing event cpython.run_stdin with no arguments.
Changed in version 3.12.5: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20) Emits audit events.
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying the -u option.
PYTHONVERBOSE
If this is set to a non-empty string it is equivalent to specifying the -v option. If set to an integer, it is equivalent
to specifying -v multiple times.
PYTHONCASEOK
If this is set, Python ignores case in import statements. This only works on Windows and macOS.
PYTHONDONTWRITEBYTECODE
If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This
is equivalent to specifying the -B option.
PYTHONPYCACHEPREFIX
If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in __pycache__
directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.
Added in version 3.8.
PYTHONHASHSEED
If this variable is not set or set to random, a random value is used to seed the hashes of str and bytes objects.
If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types
covered by the hash randomization.
Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of
python processes to share hash values.
The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash
randomization.
Added in version 3.2.3.
PYTHONINTMAXSTRDIGITS
If this variable is set to an integer, it is used to configure the interpreter’s global integer string conversion length
limitation.
Added in version 3.11.
PYTHONIOENCODING
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax
encodingname:errorhandler. Both the encodingname and the :errorhandler parts are optional and
have the same meaning as in str.encode().
For stderr, the :errorhandler part is ignored; the handler will always be 'backslashreplace'.
µ See also
PYTHONUSERBASE
Defines the user base directory, which is used to compute the path of the user site-packages
directory and installation paths for python -m pip install --user.
µ See also
PYTHONEXECUTABLE
If this environment variable is set, sys.argv[0] will be set to its value instead of the value got through the
C runtime. Only works on macOS.
PYTHONWARNINGS
This is equivalent to the -W option. If set to a comma separated string, it is equivalent to specifying -W multiple
times, with filters later in the list taking precedence over those earlier in the list.
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those
that are otherwise ignored by default):
PYTHONPROFILEIMPORTTIME
If this environment variable is set to a non-empty string, Python will show how long each import takes. This
is equivalent to setting the -X importtime option.
Added in version 3.7.
PYTHONASYNCIODEBUG
If this environment variable is set to a non-empty string, enable the debug mode of the asyncio module.
Added in version 3.4.
PYTHONMALLOC
Set the Python memory allocators and/or install debug hooks.
Set the family of memory allocators used by Python:
• default: use the default memory allocators.
• malloc: use the malloc() function of the C library for all domains (PYMEM_DOMAIN_RAW,
PYMEM_DOMAIN_MEM, PYMEM_DOMAIN_OBJ).
• pymalloc: use the pymalloc allocator for PYMEM_DOMAIN_MEM and PYMEM_DOMAIN_OBJ domains and
use the malloc() function for the PYMEM_DOMAIN_RAW domain.
Install debug hooks:
• debug: install debug hooks on top of the default memory allocators.
• malloc_debug: same as malloc but also install debug hooks.
• pymalloc_debug: same as pymalloc but also install debug hooks.
Added in version 3.6.
Changed in version 3.7: Added the "default" allocator.
PYTHONMALLOCSTATS
If set to a non-empty string, Python will print statistics of the pymalloc memory allocator every time a new
pymalloc object arena is created, and on shutdown.
This variable is ignored if the PYTHONMALLOC environment variable is used to force the malloc() allocator
of the C library, or if Python is configured without pymalloc support.
Changed in version 3.6: This variable can now also be used on Python compiled in release mode. It now has
no effect if set to an empty string.
PYTHONLEGACYWINDOWSFSENCODING
If set to a non-empty string, the default filesystem encoding and error handler mode will revert to their pre-3.6
values of ‘mbcs’ and ‘replace’, respectively. Otherwise, the new defaults ‘utf-8’ and ‘surrogatepass’ are used.
This may also be enabled at runtime with sys._enablelegacywindowsfsencoding().
Availability: Windows.
Added in version 3.6: See PEP 529 for more details.
PYTHONLEGACYWINDOWSSTDIO
If set to a non-empty string, does not use the new console reader and writer. This means that Unicode characters
will be encoded according to the active console code page, rather than using utf-8.
This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console
buffers.
Availability: Windows.
Added in version 3.6.
PYTHONCOERCECLOCALE
If set to the value 0, causes the main Python command line application to skip coercing the legacy ASCII-based
C and POSIX locales to a more capable UTF-8 based alternative.
If this variable is not set (or is set to a value other than 0), the LC_ALL locale override environment variable
is also not set, and the current locale reported for the LC_CTYPE category is either the default C locale, or else
the explicitly ASCII-based POSIX locale, then the Python CLI will attempt to configure the following locales
for the LC_CTYPE category in the order listed before loading the interpreter runtime:
• C.UTF-8
• C.utf8
• UTF-8
If setting one of these locale categories succeeds, then the LC_CTYPE environment variable will also be set
accordingly in the current process environment before the Python runtime is initialized. This ensures that in
addition to being seen by both the interpreter itself and other locale-aware components running in the same
process (such as the GNU readline library), the updated setting is also seen in subprocesses (regardless
of whether or not those processes are running a Python interpreter), as well as in operations that query the
environment rather than the current C locale (such as Python’s own locale.getdefaultlocale()).
Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically
enables the surrogateescape error handler for sys.stdin and sys.stdout (sys.stderr continues to
use backslashreplace as it does in any other locale). This stream handling behavior can be overridden
using PYTHONIOENCODING as usual.
For debugging purposes, setting PYTHONCOERCECLOCALE=warn will cause Python to emit warning messages
on stderr if either the locale coercion activates, or else if a locale that would have triggered coercion is still
active when the Python runtime is initialized.
Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale,
PYTHONUTF8 will still activate by default in legacy ASCII-based locales. Both features must be disabled
in order to force the interpreter to use ASCII instead of UTF-8 for system interfaces.
Availability: Unix.
Added in version 3.7: See PEP 538 for more details.
PYTHONDEVMODE
If this environment variable is set to a non-empty string, enable Python Development Mode, introducing ad-
ditional runtime checks that are too expensive to be enabled by default. This is equivalent to setting the -X
dev option.
objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter
displays tracebacks.
Added in version 3.11.
PYTHONPERFSUPPORT
If this variable is set to a nonzero value, it enables support for the Linux perf profiler so Python calls can be
detected by it.
If set to 0, disable Linux perf profiler support.
See also the -X perf command-line option and perf_profiling.
Added in version 3.12.
TWO
µ See also
https://www.debian.org/doc/manuals/maint-guide/first.en.html
for Debian users
https://en.opensuse.org/Portal:Packaging
for OpenSuse users
https://docs.fedoraproject.org/en-US/package-maintainers/Packaging_Tutorial_GNU_Hello/
for Fedora users
https://slackbook.org/html/package-management-making-packages.html
for Slackware users
Installing IDLE
In some cases, IDLE might not be included in your Python installation.
• For Debian and Ubuntu users:
17
Python Setup and Usage, Release 3.12.9
pkg_add -r python
For example i386 users get the 2.5.1 version of Python using:
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
./configure
make
make install
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in
the root of the Python source tree.
Á Warning
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recom-
mended instead of make install since it only installs exec_prefix/bin/pythonversion.
File/directory Meaning
exec_prefix/bin/python3 Recommended location of the interpreter.
prefix/lib/pythonversion, Recommended locations of the directories containing the standard
exec_prefix/lib/pythonversion modules.
prefix/include/pythonversion, Recommended locations of the directories containing the include files
exec_prefix/include/ needed for developing Python extensions and embedding the inter-
pythonversion preter.
2.4 Miscellaneous
To easily use Python scripts on Unix, you need to make them executable, e.g. with
$ chmod +x script
and put an appropriate Shebang line at the top of the script. A good choice is usually
#!/usr/bin/env python3
which searches for the Python interpreter in the whole PATH. However, some Unices may not have the env command,
so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2. Download, build, and install OpenSSL. Make sure you use install_sw and not install. The install_sw
target does not override openssl.cnf.
$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz
$ tar xzf openssl-VERSION
$ pushd openssl-VERSION
$ ./config \
--prefix=/usr/local/custom-openssl \
--libdir=lib \
--openssldir=/etc/ssl
$ make -j1 depend
$ make -j8
$ make install_sw
$ popd
3. Build Python with custom OpenSSL (see the configure --with-openssl and --with-openssl-rpath
options)
$ pushd python-3.x.x
$ ./configure -C \
--with-openssl=/usr/local/custom-openssl \
--with-openssl-rpath=auto \
--prefix=/usr/local/python-3.x.x
$ make -j8
$ make altinstall
® Note
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update
OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
2.4. Miscellaneous 19
Python Setup and Usage, Release 3.12.9
THREE
CONFIGURE PYTHON
make regen-all
make regen-stdlib-module-names
make regen-limited-abi
make regen-configure
The Makefile.pre.in file documents generated files, their inputs, and tools used to regenerate them. Search for
regen-* make targets.
The generated files can change depending on the exact autoconf-archive, aclocal and pkg-config versions.
21
Python Setup and Usage, Release 3.12.9
./configure --help
Default: /usr/share/zoneinfo:/usr/lib/zoneinfo:/usr/share/lib/zoneinfo:/etc/
zoneinfo.
--without-c-locale-coercion
Disable C locale coercion to a UTF-8 based locale (enabled by default).
Don’t define the PY_COERCE_C_LOCALE macro.
See PYTHONCOERCECLOCALE and the PEP 538.
--without-freelists
Disable all freelists except the empty tuple singleton.
Added in version 3.11.
--with-platlibdir=DIRNAME
Python library directory name (default is lib).
Fedora and SuSE use lib64 on 64-bit platforms.
See sys.platlibdir.
Added in version 3.9.
--with-wheel-pkg-dir=PATH
Directory of wheel packages used by the ensurepip module (none by default).
Some Linux distribution packaging policies recommend against bundling dependencies. For example, Fedora
installs wheel packages in the /usr/share/python-wheels/ directory and don’t install the ensurepip.
_bundled package.
--enable-wasm-pthreads
Turn on pthreads support for WASM.
Added in version 3.11.
® Note
During the build, you may encounter compiler warnings about profile data not being available for
some source files. These warnings are harmless, as only a subset of the code is exercised dur-
ing profile data acquisition. To disable these warnings on Clang, manually suppress them by adding
-Wno-profile-instr-unprofiled to CFLAGS.
PROFILE_TASK
Environment variable used in the Makefile: Python command line arguments for the PGO generation task.
Default: -m test --pgo --timeout=$(TESTTIMEOUT).
Added in version 3.8.
--with-lto=[full|thin|no|yes]
Enable Link Time Optimization (LTO) in any build (disabled by default).
The C compiler Clang requires llvm-ar for LTO (ar on macOS), as well as an LTO-aware linker (ld.gold
or lld).
Added in version 3.6.
Added in version 3.11: To use ThinLTO feature, use --with-lto=thin on Clang.
Changed in version 3.12: Use ThinLTO as the default optimization policy on Clang if the compiler accepts
the flag.
--enable-bolt
Enable usage of the BOLT post-link binary optimizer (disabled by default).
BOLT is part of the LLVM project but is not always included in their binary distributions. This flag requires
that llvm-bolt and merge-fdata are available.
BOLT is still a fairly new project so this flag should be considered experimental for now. Because this tool
operates on machine code its success is dependent on a combination of the build environment + the other
optimization configure args + the CPU architecture, and not all combinations are supported. BOLT versions
before LLVM 16 are known to crash BOLT under some scenarios. Use of LLVM 16 or newer for BOLT
optimization is strongly encouraged.
The BOLT_INSTRUMENT_FLAGS and BOLT_APPLY_FLAGS configure variables can be defined to override
the default set of arguments for llvm-bolt to instrument and apply BOLT data to binaries, respectively.
Added in version 3.12.
--with-computed-gotos
Enable computed gotos in evaluation loop (enabled by default on supported compilers).
--without-pymalloc
Disable the specialized Python memory allocator pymalloc (enabled by default).
See also PYTHONMALLOC environment variable.
--without-doc-strings
Disable static documentation strings to reduce the memory footprint (enabled by default). Documentation
strings defined in Python are not affected.
Don’t define the WITH_DOC_STRINGS macro.
See the PyDoc_STRVAR() macro.
--enable-profiling
Enable C-level code profiling with gprof (disabled by default).
--with-strict-overflow
Add -fstrict-overflow to the C compiler flags (by default we add -fno-strict-overflow instead).
--with-valgrind
Enable Valgrind support (default is no).
--with-dtrace
Enable DTrace support (default is no).
See Instrumenting CPython with DTrace and SystemTap.
Added in version 3.6.
--with-address-sanitizer
Enable AddressSanitizer memory error detector, asan (default is no).
Added in version 3.6.
--with-memory-sanitizer
Enable MemorySanitizer allocation error detector, msan (default is no).
Added in version 3.6.
--with-undefined-behavior-sanitizer
Enable UndefinedBehaviorSanitizer undefined behaviour detector, ubsan (default is no).
Added in version 3.6.
--with-libc=STRING
Override libc C library to STRING (default is system-dependent).
--with-openssl=DIR
Root of the OpenSSL directory.
Added in version 3.7.
--with-openssl-rpath=[no|auto|DIR]
Set runtime library directory (rpath) for OpenSSL libraries:
• no (default): don’t set rpath;
• auto: auto-detect rpath from --with-openssl and pkg-config;
• DIR: set an explicit rpath.
Added in version 3.10.
--enable-universalsdk=SDKDIR
Create a universal binary build. SDKDIR specifies which macOS SDK should be used to perform the build
(default is no).
--enable-framework
--enable-framework=INSTALLDIR
Create a Python.framework rather than a traditional Unix install. Optional INSTALLDIR specifies the instal-
lation path (default is no).
--with-universal-archs=ARCH
Specify the kind of universal binary that should be created. This option is only valid when
--enable-universalsdk is set.
Options:
• universal2 (x86-64 and arm64);
• 32-bit (PPC and i386);
• 64-bit (PPC64 and x86-64);
• 3-way (i386, PPC and x86-64);
• intel (i386 and x86-64);
• intel-32 (i386);
• intel-64 (x86-64);
• all (PPC, i386, PPC64 and x86-64).
Note that values for this configuration item are not the same as the identifiers used for universal binary wheels
on macOS. See the Python Packaging User Guide for details on the packaging platform compatibility tags used
on macOS
--with-framework-name=FRAMEWORK
Specify the name for the python framework on macOS only valid when --enable-framework is set (default:
Python).
# config.site-aarch64
ac_cv_buggy_getaddrinfo=no
ac_cv_file__dev_ptmx=yes
ac_cv_file__dev_ptc=no
CONFIG_SITE=config.site-aarch64 ../configure \
--build=x86_64-pc-linux-gnu \
--host=aarch64-unknown-linux-gnu \
--with-build-python=../x86_64/python
3.4.4 C extensions
Some C extensions are built as built-in modules, like the sys module. They are built with the
Py_BUILD_CORE_BUILTIN macro defined. Built-in modules have no __file__ attribute:
Other C extensions are built as dynamic libraries, like the _asyncio module. They are built with the
Py_BUILD_CORE_MODULE macro defined. Example on Linux x86-64:
>>> _asyncio.__file__
'/usr/lib64/python3.9/lib-dynload/_asyncio.cpython-39-x86_64-linux-gnu.so'
Modules/Setup is used to generate Makefile targets to build C extensions. At the beginning of the files, C extensions
are built as built-in modules. Extensions defined after the *shared* marker are built as dynamic libraries.
The PyAPI_FUNC(), PyAPI_DATA() and PyMODINIT_FUNC macros of Include/exports.h are defined dif-
ferently depending if the Py_BUILD_CORE_MODULE macro is defined:
• Use Py_EXPORTED_SYMBOL if the Py_BUILD_CORE_MODULE is defined
• Use Py_IMPORTED_SYMBOL otherwise.
If the Py_BUILD_CORE_BUILTIN macro is used by mistake on a C extension built as a shared library, its
PyInit_xxx() function is not exported, causing an ImportError on import.
PY_CFLAGS
Default: $(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS).
PY_CFLAGS_NODIST
Default: $(CONFIGURE_CFLAGS_NODIST) $(CFLAGS_NODIST) -I$(srcdir)/Include/internal.
Added in version 3.5.
PY_STDMODULE_CFLAGS
C flags used for building the interpreter object files.
Default: $(PY_CFLAGS) $(PY_CFLAGS_NODIST) $(PY_CPPFLAGS) $(CFLAGSFORSHARED).
Added in version 3.7.
PY_CORE_CFLAGS
Default: $(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE.
Added in version 3.2.
PY_BUILTIN_MODULE_CFLAGS
Compiler flags to build a standard library extension module as a built-in module, like the posix module.
Default: $(PY_STDMODULE_CFLAGS) -DPy_BUILD_CORE_BUILTIN.
Added in version 3.8.
PURIFY
Purify command. Purify is a memory debugger program.
Default: empty string (not used).
LIBS
Linker flags to pass libraries to the linker when linking the Python executable.
Example: -lrt.
LDSHARED
Command to build a shared library.
Default: @LDSHARED@ $(PY_LDFLAGS).
BLDSHARED
Command to build libpython shared library.
Default: @BLDSHARED@ $(PY_CORE_LDFLAGS).
PY_LDFLAGS
Default: $(CONFIGURE_LDFLAGS) $(LDFLAGS).
PY_LDFLAGS_NODIST
Default: $(CONFIGURE_LDFLAGS_NODIST) $(LDFLAGS_NODIST).
Added in version 3.8.
PY_CORE_LDFLAGS
Linker flags used for building the interpreter object files.
Added in version 3.8.
FOUR
This document aims to give an overview of Windows-specific behaviour you should know about when using Python
on Microsoft Windows.
Unlike most Unix systems and services, Windows does not include a system supported installation of Python. To
make Python available, the CPython team has compiled Windows installers with every release for many years. These
installers are primarily intended to add a per-user installation of Python, with the core interpreter and library being
used by a single user. The installer is also able to install for all users of a single machine, and a separate ZIP file is
available for application-local distributions.
As specified in PEP 11, a Python release only supports a Windows platform while Microsoft considers the platform
under extended support. This means that Python 3.12 supports Windows 8.1 and newer. If you require Windows 7
support, please install Python 3.8.
There are a number of different installers available for Windows, each with certain benefits and downsides.
The full installer contains all components and is the best option for developers using Python for any kind of project.
The Microsoft Store package is a simple installation of Python that is suitable for running scripts and packages, and
using IDLE or other development environments. It requires Windows 10 and above, but can be safely installed
without corrupting other programs. It also provides many convenient commands for launching Python and its tools.
The nuget.org packages are lightweight installations intended for continuous integration systems. It can be used to
build Python packages or run scripts, but is not updateable and has no user interface tools.
The embeddable package is a minimal package of Python suitable for embedding into a larger application.
35
Python Setup and Usage, Release 3.12.9
In the latest versions of Windows, this limitation can be expanded to approximately 32,000 characters. Your admin-
istrator will need to activate the “Enable Win32 long paths” group policy, or set LongPathsEnabled to 1 in the
registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem.
This allows the open() function, the os module and most other path functionality to accept and return paths longer
than 260 characters.
After changing the above option, no further configuration is required.
Changed in version 3.6: Support for long paths was enabled in Python.
Name Description
/passive to display progress without requiring user interaction
/quiet to install/uninstall without displaying any UI
/simple to prevent user customization
/uninstall to remove Python (without confirmation)
/layout [directory] to pre-download all components
/log [filename] to specify log files location
All other options are passed as name=value, where the value is usually 0 to disable a feature, 1 to enable a feature,
or a path. The full list of available options is shown below.
For example, to silently install a default, system-wide Python installation, you could use the following command (from
an elevated command prompt):
To allow users to easily install a personal copy of Python without the test suite, you could provide a shortcut with the
following command. This will display a simplified initial page and disallow customization:
(Note that omitting the launcher also omits file associations, and is only recommended for per-user installs when there
is also a system-wide installation that included the launcher.)
The options listed above can also be provided in a file named unattend.xml alongside the executable. This file
specifies a list of options and values. When a value is provided as an attribute, it will be converted to a number if
possible. Values provided as element text are always left as strings. This example file sets the same options as the
previous example:
<Options>
<Option Name="InstallAllUsers" Value="no" />
<Option Name="Include_launcher" Value="0" />
<Option Name="Include_test" Value="no" />
<Option Name="SimpleInstall" Value="yes" />
<Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
</Options>
You may also specify the /quiet option to hide the progress display.
Á Warning
Python will always be available for free on the Microsoft Store. If you are asked to pay for it, you have not
selected the correct package.
After installation, Python may be launched by finding it in Start. Alternatively, it will be available from any Command
Prompt or PowerShell session by typing python. Further, pip and IDLE may be used by typing pip or idle. IDLE
can also be found in Start.
All three commands are also available with version number suffixes, for example, as python3.exe and python3.
x.exe as well as python.exe (where 3.x is the specific version you want to launch, such as 3.12). Open “Manage
App Execution Aliases” through Start to select which version of Python is associated with each command. It is
recommended to make sure that pip and idle are consistent with whichever version of python is selected.
Virtual environments can be created with python -m venv and activated and used as normal.
If you have installed another version of Python and added it to your PATH variable, it will be available as python.exe
rather than the one from the Microsoft Store. To access the new installation, use python3.exe or python3.x.exe.
The py.exe launcher will detect this Python installation, but will prefer installations from the traditional installer.
To remove Python, open Settings and use Apps and Features, or else find Python in Start and right-click to select
Uninstall. Uninstalling will remove all packages you installed directly into this Python installation, but will not remove
any virtual environments
>>> import os
>>> test_file = 'C:\\Users\\example\\AppData\\Local\\test.txt'
>>> os.path.realpath(test_file)
'C:\\Users\\example\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_
,→qbz5n2kfra8p0\\LocalCache\\Local\\test.txt'
• Reading from HKLM\\Software is allowed and results are merged with the registry.dat file in the pack-
age.
• Writing to HKLM\\Software is not allowed if the corresponding key/value exists, i.e. modifying existing
keys.
• Writing to HKLM\\Software is allowed as long as a corresponding key/value does not exist in the package
and the user has the correct access permissions.
For more detail on the technical basis for these limitations, please consult Microsoft’s documentation on packaged
full-trust apps, currently available at docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-
scenes
To select a particular version, add a -Version 3.x.y. The output directory may be changed from ., and the
package will be installed into a subdirectory. By default, the subdirectory is named the same as the package, and
without the -ExcludeVersion option this name will include the specific version installed. Inside the subdirectory
is a tools directory that contains the Python installation:
# Without -ExcludeVersion
> .\python.3.5.2\tools\python.exe -V
Python 3.5.2
# With -ExcludeVersion
> .\python\tools\python.exe -V
Python 3.5.2
In general, nuget packages are not upgradeable, and newer versions should be installed side-by-side and referenced
using the full path. Alternatively, delete the package directory manually and install it again. Many CI systems will
do this automatically if they do not preserve files between builds.
Alongside the tools directory is a build\native directory. This contains a MSBuild properties file python.
props that can be used in a C++ project to reference the Python install. Including the settings will automatically use
the headers and import libraries in your build.
The package information pages on nuget.org are www.nuget.org/packages/python for the 64-bit version and
www.nuget.org/packages/pythonx86 for the 32-bit version.
When extracted, the embedded distribution is (almost) fully isolated from the user’s system, including environment
variables, system registry settings, and installed packages. The standard library is included as pre-compiled and opti-
mized .pyc files in a ZIP, and python3.dll, python37.dll, python.exe and pythonw.exe are all provided.
Tcl/tk (including all dependents, such as Idle), pip and the Python documentation are not included.
® Note
The embedded distribution does not include the Microsoft C Runtime and it is the responsibility of the appli-
cation installer to provide this. The runtime may have already been installed on a user’s system previously or
automatically via Windows Update, and can be detected by finding ucrtbase.dll in the system directory.
Third-party packages should be installed by the application installer alongside the embedded distribution. Using pip
to manage dependencies as for a regular Python installation is not supported with this distribution, though with some
care it may be possible to include and use pip for automatic updates. In general, third-party packages should be
treated as part of the application (“vendoring”) so that the developer can ensure compatibility with newer versions
before providing updates to users.
The two recommended use cases for this distribution are described below.
These changes will apply to any further commands executed in that console, and will be inherited by any applications
started from the console.
Including the variable name within percent signs will expand to the existing value, allowing you to add your new
value at either the start or the end. Modifying PATH by adding the directory containing python.exe to the start is
a common way to ensure the correct version of Python is launched.
To permanently modify the default environment variables, click Start and search for ‘edit environment variables’, or
open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you
can add or modify User and System variables. To change System variables, you need non-restricted access to your
machine (i.e. Administrator rights).
® Note
Windows will concatenate User variables after System variables, which may cause unexpected results when mod-
ifying PATH.
The PYTHONPATH variable is used by all versions of Python, so you should not permanently configure it unless
the listed paths only include code that is compatible with all of your installed Python versions.
µ See also
https://learn.microsoft.com/windows/win32/procthread/environment-variables
Overview of environment variables on Windows
https://learn.microsoft.com/windows-server/administration/windows-commands/set_1
The set command, for temporarily modifying environment variables
https://learn.microsoft.com/windows-server/administration/windows-commands/setx
The setx command, for permanently modifying environment variables
® Note
Even when UTF-8 mode is disabled, Python uses UTF-8 by default on Windows for:
• Console I/O including standard I/O (see PEP 528 for details).
• The filesystem encoding (see PEP 529 for details).
py
You should find that the latest version of Python you have installed is started - it can be exited as normal, and any
additional command-line arguments specified will be sent directly to Python.
If you have multiple versions of Python installed (e.g., 3.7 and 3.12) you will have noticed that Python 3.12 was
started - to launch Python 3.7, try the command:
py -3.7
If you want the latest version of Python 2 you have installed, try the command:
py -2
If you see the following error, you do not have the launcher installed:
The command:
py --list
The short form of the argument (-3) only ever selects from core Python releases, and not other distributions. However,
the longer form (-V:3) will select from any.
The Company is matched on the full string, case-insenitive. The Tag is matched oneither the full string, or a prefix,
provided the next character is a dot or a hyphen. This allows -V:3.1 to match 3.1-32, but not 3.10. Tags are
sorted using numerical ordering (3.10 is newer than 3.1), but are compared using text (-V:3.01 does not match
3.1).
Virtual environments
Added in version 3.5.
If the launcher is run with no explicit Python version specification, and a virtual environment (created with the
standard library venv module or the external virtualenv tool) active, the launcher will run the virtual environment’s
interpreter rather than the global one. To run the global interpreter, either deactivate the virtual environment, or
explicitly specify the global Python version.
From a script
Let’s create a test Python script - create a file called hello.py with the following contents
#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
py hello.py
You should notice the version number of your latest Python 2.x installation is printed. Now try changing the first line
to be:
#! python3
Re-executing the command should now print the latest Python 3.x information. As with the above command-line
examples, you can specify a more explicit version qualifier. Assuming you have Python 3.7 installed, try changing
the first line to #! python3.7 and you should find the 3.7 version information printed.
Note that unlike interactive use, a bare “python” will use the latest version of Python 2.x that you have installed.
This is for backward compatibility and for compatibility with Unix, where the command python typically refers to
Python 2.
#! /usr/bin/python
The default Python will be located and used. As many Python scripts written to work on Unix will already have this
line, you should find these scripts can be used by the launcher without modification. If you are writing a new script
on Windows which you hope will be useful on Unix, you should use one of the shebang lines starting with /usr.
Any of the above virtual commands can be suffixed with an explicit version (either just the major version, or the
major and minor version). Furthermore the 32-bit version can be requested by adding “-32” after the minor version.
I.e. /usr/bin/python3.7-32 will request usage of the 32-bit python 3.7.
Added in version 3.7: Beginning with python launcher 3.7 it is possible to request 64-bit version by the “-64” suffix.
Furthermore it is possible to specify a major and architecture without minor (i.e. /usr/bin/python3-64).
Changed in version 3.11: The “-64” suffix is deprecated, and now implies “any architecture that is not provably
i386/32-bit”. To request a specific environment, use the new -V:TAG argument with the complete tag.
The /usr/bin/env form of shebang line has one further special property. Before looking for installed Python inter-
preters, this form will search the executable PATH for a Python executable matching the name provided as the first ar-
gument. This corresponds to the behaviour of the Unix env program, which performs a PATH search. If an executable
matching the first argument after the env command cannot be found, but the argument starts with python, it will be
handled as described for the other virtual commands. The environment variable PYLAUNCHER_NO_SEARCH_PATH
may be set (to any value) to skip this search of PATH.
Shebang lines that do not match any of these patterns are looked up in the [commands] section of the launcher’s
.INI file. This may be used to handle certain commands in a way that makes sense for your system. The name of the
command must be a single argument (no spaces in the shebang executable), and the value substituted is the full path
to the executable (additional arguments specified in the .INI will be quoted as part of the filename).
[commands]
/bin/xpython=C:\Program Files\XPython\python.exe
Any commands not found in the .INI file are treated as Windows executable paths that are absolute or relative to the
directory containing the script file. This is a convenience for Windows-only scripts, such as those generated by an
installer, since the behavior is not compatible with Unix-style shells. These paths may be quoted, and may include
multiple arguments, after which the path to the script and any additional arguments will be appended.
#! /usr/bin/python -v
4.8.4 Customization
Customization via INI files
Two .ini files will be searched by the launcher - py.ini in the current user’s application data directory
(%LOCALAPPDATA% or $env:LocalAppData) and py.ini in the same directory as the launcher. The same .ini
files are used for both the ‘console’ version of the launcher (i.e. py.exe) and for the ‘windows’ version (i.e. pyw.exe).
Customization specified in the “application directory” will have precedence over the one next to the executable, so a
user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini
file.
[defaults]
python=3.7
[defaults]
python=3
python3=3.7
4.8.5 Diagnostics
If an environment variable PYLAUNCHER_DEBUG is set (to any value), the launcher will print diagnostic information
to stderr (i.e. to the console). While this information manages to be simultaneously verbose and terse, it should allow
you to see what versions of Python were located, why a particular version was chosen and the exact command-line
used to execute the target Python. It is primarily intended for testing and debugging.
deduce the “Python Home”. If a Python home is found, the relevant sub-directories added to sys.path (Lib,
plat-win, etc) are based on that folder. Otherwise, the core Python path is constructed from the PythonPath
stored in the registry.
• If the Python Home cannot be located, no PYTHONPATH is specified in the environment, and no registry entries
can be found, a default path with relative entries is used (e.g. .\Lib;.\plat-win, etc).
If a pyvenv.cfg file is found alongside the main executable or in the directory one level above the executable, the
following variations apply:
• If home is an absolute path and PYTHONHOME is not set, this path is used instead of the path to the main
executable when deducing the home location.
The end result of all this is:
• When running python.exe, or any other .exe in the main Python directory (either an installed version, or
directly from the PCbuild directory), the core path is deduced, and the core paths in the registry are ignored.
Other “application paths” in the registry are always read.
• When Python is hosted in another .exe (different directory, embedded via COM, etc), the “Python Home” will
not be deduced, so the core path from the registry is used. Other “application paths” in the registry are always
read.
• If Python can’t find its home and there are no registry value (frozen .exe, some very strange installation setup)
you get a path with some default, but relative, paths.
For those who want to bundle Python into their application or distribution, the following advice will prevent conflicts
with other installations:
• Include a ._pth file alongside your executable containing the directories to include. This will ignore paths
listed in the registry and environment variables, and also ignore site unless import site is listed.
• If you are loading python3.dll or python37.dll in your own executable, explicitly call Py_SetPath()
or (at least) Py_SetProgramName() before Py_Initialize().
• Clear and/or overwrite PYTHONPATH and set PYTHONHOME before launching python.exe from your appli-
cation.
• If you cannot use the previous suggestions (for example, you are a distribution that allows people to run
python.exe directly), ensure that the landmark file (Lib\os.py) exists in your install directory. (Note
that it will not be detected inside a ZIP file, but a correctly named ZIP file will be detected instead.)
These will ensure that the files in a system-wide installation will not take precedence over the copy of the standard
library bundled with your application. Otherwise, your users may experience problems using your application. Note
that the first suggestion is the best, as the others may still be susceptible to non-standard paths in the registry and user
site-packages.
Changed in version 3.6: Add ._pth file support and removes applocal option from pyvenv.cfg.
Changed in version 3.6: Add pythonXX.zip as a potential landmark when directly adjacent to the executable.
Deprecated since version 3.6: Modules specified in the registry under Modules (not PythonPath) may be imported
by importlib.machinery.WindowsRegistryFinder. This finder is enabled on Windows in 3.6.0 and earlier,
but may need to be explicitly added to sys.meta_path in the future.
4.10.1 PyWin32
The PyWin32 module by Mark Hammond is a collection of modules for advanced Windows-specific support. This
includes utilities for:
• Component Object Model (COM)
• Win32 API calls
• Registry
• Event log
• Microsoft Foundation Classes (MFC) user interfaces
PythonWin is a sample MFC application shipped with PyWin32. It is an embeddable IDE with a built-in debugger.
µ See also
4.10.2 cx_Freeze
cx_Freeze wraps Python scripts into executable Windows programs (*.exe files). When you have done this, you
can distribute your application without requiring your users to install Python.
FIVE
Author
Bob Savage <bobsavage@mac.com>
Python on a Mac running macOS is in principle very similar to Python on any other Unix platform, but there are a
number of additional features such as the integrated development environment (IDE) and the Package Manager that
are worth pointing out.
® Note
IDLE includes a Help menu that allows you to access Python documentation. If you are completely new to Python
you should start reading the tutorial introduction in that document.
If you are familiar with Python on other Unix platforms you should read the section on running Python scripts from
the Unix shell.
53
Python Setup and Usage, Release 3.12.9
products/bbedit/index.html) are good choices, as is TextMate (see https://macromates.com). Other editors include
MacVim (https://macvim.org) and Aquamacs (https://aquamacs.org).
To run your script from the Terminal window you must make sure that /usr/local/bin is in your shell search
path.
To run your script from the Finder you have two options:
• Drag it to Python Launcher.
• Select Python Launcher as the default application to open your script (or any .py script) through the finder
Info window and double-click it. Python Launcher has various preferences to control how your script is
launched. Option-dragging allows you to change these for one invocation, or use its Preferences menu to
change things globally.
5.1.3 Configuration
Python on macOS honors all standard Unix environment variables such as PYTHONPATH , but setting these variables
for programs started from the Finder is non-standard as the Finder does not read your .profile or .cshrc at
startup. You need to create a file ~/.MacOSX/environment.plist. See Apple’s Technical Q&A QA1067 for
details.
For more information on installation Python packages, see section Installing Additional Python Packages.
SIX
There are a number of IDEs that support Python programming language. Many editors and IDEs provide syntax
highlighting, debugging tools, and PEP 8 checks.
57
Python Setup and Usage, Release 3.12.9
GLOSSARY
>>>
The default Python prompt of the interactive shell. Often seen for code examples which can be executed
interactively in the interpreter.
...
Can refer to:
• The default Python prompt of the interactive shell when entering the code for an indented code block,
when within a pair of matching left and right delimiters (parentheses, square brackets, curly braces or
triple quotes), or after specifying a decorator.
• The Ellipsis built-in constant.
2to3
A tool that tries to convert Python 2.x code to Python 3.x code by handling most of the incompatibilities which
can be detected by parsing the source and traversing the parse tree.
2to3 is available in the standard library as lib2to3; a standalone entry point is provided as Tools/scripts/
2to3. See 2to3-reference.
abstract base class
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques
like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual
subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and
issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data struc-
tures (in the collections.abc module), numbers (in the numbers module), streams (in the io module),
import finders and loaders (in the importlib.abc module). You can create your own ABCs with the abc
module.
annotation
A label associated with a variable, a class attribute or a function parameter or return value, used by convention
as a type hint.
Annotations of local variables cannot be accessed at runtime, but annotations of global variables, class at-
tributes, and functions are stored in the __annotations__ special attribute of modules, classes, and func-
tions, respectively.
See variable annotation, function annotation, PEP 484 and PEP 526, which describe this functionality. Also
see annotations-howto for best practices on working with annotations.
argument
A value passed to a function (or method) when calling the function. There are two kinds of argument:
• keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a
value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following
calls to complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
59
Python Setup and Usage, Release 3.12.9
• positional argument: an argument that is not a keyword argument. Positional arguments can appear at the
beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3
and 5 are both positional arguments in the following calls:
complex(3, 5)
complex(*(3, 5))
Arguments are assigned to the named local variables in a function body. See the calls section for the rules
governing this assignment. Syntactically, any expression can be used to represent an argument; the evaluated
value is assigned to the local variable.
See also the parameter glossary entry, the FAQ question on the difference between arguments and parameters,
and PEP 362.
asynchronous context manager
An object which controls the environment seen in an async with statement by defining __aenter__() and
__aexit__() methods. Introduced by PEP 492.
asynchronous generator
A function which returns an asynchronous generator iterator. It looks like a coroutine function defined with
async def except that it contains yield expressions for producing a series of values usable in an async
for loop.
Usually refers to an asynchronous generator function, but may refer to an asynchronous generator iterator in
some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.
An asynchronous generator function may contain await expressions as well as async for, and async with
statements.
asynchronous generator iterator
An object created by a asynchronous generator function.
This is an asynchronous iterator which when called using the __anext__() method returns an awaitable object
which will execute the body of the asynchronous generator function until the next yield expression.
Each yield temporarily suspends processing, remembering the execution state (including local variables and
pending try-statements). When the asynchronous generator iterator effectively resumes with another awaitable
returned by __anext__(), it picks up where it left off. See PEP 492 and PEP 525.
asynchronous iterable
An object, that can be used in an async for statement. Must return an asynchronous iterator from its
__aiter__() method. Introduced by PEP 492.
asynchronous iterator
An object that implements the __aiter__() and __anext__() methods. __anext__() must return an
awaitable object. async for resolves the awaitables returned by an asynchronous iterator’s __anext__()
method until it raises a StopAsyncIteration exception. Introduced by PEP 492.
attribute
A value associated with an object which is usually referenced by name using dotted expressions. For example,
if an object o has an attribute a it would be referenced as o.a.
It is possible to give an object an attribute whose name is not an identifier as defined by identifiers, for example
using setattr(), if the object allows it. Such an attribute will not be accessible using a dotted expression,
and would instead need to be retrieved with getattr().
awaitable
An object that can be used in an await expression. Can be a coroutine or an object with an __await__()
method. See also PEP 492.
BDFL
Benevolent Dictator For Life, a.k.a. Guido van Rossum, Python’s creator.
binary file
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary mode
60 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
See also text file for a file object able to read and write str objects.
borrowed reference
In Python’s C API, a borrowed reference is a reference to an object, where the code using the object does not
own the reference. It becomes a dangling pointer if the object is destroyed. For example, a garbage collection
can remove the last strong reference to the object and so destroy it.
Calling Py_INCREF() on the borrowed reference is recommended to convert it to a strong reference in-place,
except when the object cannot be destroyed before the last usage of the borrowed reference. The Py_NewRef()
function can be used to create a new strong reference.
bytes-like object
An object that supports the bufferobjects and can export a C-contiguous buffer. This includes all bytes,
bytearray, and array.array objects, as well as many common memoryview objects. Bytes-like objects
can be used for various operations that work with binary data; these include compression, saving to a binary
file, and sending over a socket.
Some operations need the binary data to be mutable. The documentation often refers to these as “read-write
bytes-like objects”. Example mutable buffer objects include bytearray and a memoryview of a bytearray.
Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”);
examples of these include bytes and a memoryview of a bytes object.
bytecode
Python source code is compiled into bytecode, the internal representation of a Python program in the CPython
interpreter. The bytecode is also cached in .pyc files so that executing the same file is faster the second time
(recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a
virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are
not expected to work between different Python virtual machines, nor to be stable between Python releases.
A list of bytecode instructions can be found in the documentation for the dis module.
callable
A callable is an object that can be called, possibly with a set of arguments (see argument), with the following
syntax:
A function, and by extension a method, is a callable. An instance of a class that implements the __call__()
method is also a callable.
callback
A subroutine function which is passed as an argument to be executed at some point in the future.
class
A template for creating user-defined objects. Class definitions normally contain method definitions which
operate on instances of the class.
class variable
A variable defined in a class and intended to be modified only at class level (i.e., not in an instance of the class).
complex number
An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and
an imaginary part. Imaginary numbers are real multiples of the imaginary unit (the square root of -1), often
written i in mathematics or j in engineering. Python has built-in support for complex numbers, which are
written with this latter notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to com-
plex equivalents of the math module, use cmath. Use of complex numbers is a fairly advanced mathematical
feature. If you’re not aware of a need for them, it’s almost certain you can safely ignore them.
context manager
An object which controls the environment seen in a with statement by defining __enter__() and
__exit__() methods. See PEP 343.
61
Python Setup and Usage, Release 3.12.9
context variable
A variable which can have different values depending on its context. This is similar to Thread-Local Storage in
which each execution thread may have a different value for a variable. However, with context variables, there
may be several contexts in one execution thread and the main usage for context variables is to keep track of
variables in concurrent asynchronous tasks. See contextvars.
contiguous
A buffer is considered contiguous exactly if it is either C-contiguous or Fortran contiguous. Zero-dimensional
buffers are C and Fortran contiguous. In one-dimensional arrays, the items must be laid out in memory next
to each other, in order of increasing indexes starting from zero. In multidimensional C-contiguous arrays, the
last index varies the fastest when visiting items in order of memory address. However, in Fortran contiguous
arrays, the first index varies the fastest.
coroutine
Coroutines are a more generalized form of subroutines. Subroutines are entered at one point and exited at
another point. Coroutines can be entered, exited, and resumed at many different points. They can be imple-
mented with the async def statement. See also PEP 492.
coroutine function
A function which returns a coroutine object. A coroutine function may be defined with the async def state-
ment, and may contain await, async for, and async with keywords. These were introduced by PEP
492.
CPython
The canonical implementation of the Python programming language, as distributed on python.org. The term
“CPython” is used when necessary to distinguish this implementation from others such as Jython or IronPython.
decorator
A function returning another function, usually applied as a function transformation using the @wrapper syntax.
Common examples for decorators are classmethod() and staticmethod().
The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equiv-
alent:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
The same concept exists for classes, but is less commonly used there. See the documentation for function
definitions and class definitions for more about decorators.
descriptor
Any object which defines the methods __get__(), __set__(), or __delete__(). When a class attribute
is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to get,
set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor,
the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of
Python because they are the basis for many features including functions, methods, properties, class methods,
static methods, and reference to super classes.
For more information about descriptors’ methods, see descriptors or the Descriptor How To Guide.
dictionary
An associative array, where arbitrary keys are mapped to values. The keys can be any object with __hash__()
and __eq__() methods. Called a hash in Perl.
dictionary comprehension
A compact way to process all or part of the elements in an iterable and return a dictionary with the re-
sults. results = {n: n ** 2 for n in range(10)} generates a dictionary containing key n mapped
to value n ** 2. See comprehensions.
62 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
dictionary view
The objects returned from dict.keys(), dict.values(), and dict.items() are called dictionary views.
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the
view reflects these changes. To force the dictionary view to become a full list use list(dictview). See
dict-views.
docstring
A string literal which appears as the first expression in a class, function or module. While ignored when the
suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class,
function or module. Since it is available via introspection, it is the canonical place for documentation of the
object.
duck-typing
A programming style which does not look at an object’s type to determine if it has the right interface; instead,
the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be
a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility
by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). (Note,
however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs
hasattr() tests or EAFP programming.
EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of
valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is
characterized by the presence of many try and except statements. The technique contrasts with the LBYL
style common to many other languages such as C.
expression
A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of
expression elements like literals, names, attribute access, operators or function calls which all return a value. In
contrast to many other languages, not all language constructs are expressions. There are also statements which
cannot be used as expressions, such as while. Assignments are also statements, not expressions.
extension module
A module written in C or C++, using Python’s C API to interact with the core and with user code.
f-string
String literals prefixed with 'f' or 'F' are commonly called “f-strings” which is short for formatted string
literals. See also PEP 498.
file object
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of
storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.).
File objects are also called file-like objects or streams.
There are actually three categories of file objects: raw binary files, buffered binary files and text files. Their
interfaces are defined in the io module. The canonical way to create a file object is by using the open()
function.
file-like object
A synonym for file object.
filesystem encoding and error handler
Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to
the operating system.
The filesystem encoding must guarantee to successfully decode all bytes below 128. If the file system encoding
fails to provide this guarantee, API functions can raise UnicodeError.
The sys.getfilesystemencoding() and sys.getfilesystemencodeerrors() functions can be
used to get the filesystem encoding and error handler.
The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() func-
tion: see filesystem_encoding and filesystem_errors members of PyConfig.
63
Python Setup and Usage, Release 3.12.9
function
A series of statements which returns some value to a caller. It can also be passed zero or more arguments which
may be used in the execution of the body. See also parameter, method, and the function section.
function annotation
An annotation of a function parameter or return value.
Function annotations are usually used for type hints: for example, this function is expected to take two int
arguments and is also expected to have an int return value:
garbage collection
The process of freeing memory when it is not used anymore. Python performs garbage collection via reference
counting and a cyclic garbage collector that is able to detect and break reference cycles. The garbage collector
can be controlled using the gc module.
generator
A function which returns a generator iterator. It looks like a normal function except that it contains yield
expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the
next() function.
Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where
the intended meaning isn’t clear, using the full terms avoids ambiguity.
generator iterator
An object created by a generator function.
Each yield temporarily suspends processing, remembering the execution state (including local variables and
pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to
functions which start fresh on every invocation).
generator expression
An expression that returns an iterator. It looks like a normal expression followed by a for clause defining a
64 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
loop variable, range, and an optional if clause. The combined expression generates values for an enclosing
function:
generic function
A function composed of multiple functions implementing the same operation for different types. Which im-
plementation should be used during a call is determined by the dispatch algorithm.
See also the single dispatch glossary entry, the functools.singledispatch() decorator, and PEP 443.
generic type
A type that can be parameterized; typically a container class such as list or dict. Used for type hints and
annotations.
For more details, see generic alias types, PEP 483, PEP 484, PEP 585, and the typing module.
GIL
See global interpreter lock.
global interpreter lock
The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at
a time. This simplifies the CPython implementation by making the object model (including critical built-in
types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier
for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor
machines.
However, some extension modules, either standard or third-party, are designed so as to release the GIL when
doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when
doing I/O.
Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity)
have not been successful because performance suffered in the common single-processor case. It is believed
that overcoming this performance issue would make the implementation much more complicated and therefore
costlier to maintain.
hash-based pyc
A bytecode cache file that uses the hash rather than the last-modified time of the corresponding source file to
determine its validity. See pyc-invalidation.
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which
compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the
hash value internally.
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries)
are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable.
Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except
with themselves), and their hash value is derived from their id().
IDLE
An Integrated Development and Learning Environment for Python. idle is a basic editor and interpreter envi-
ronment which ships with the standard distribution of Python.
immortal
Immortal objects are a CPython implementation detail introduced in PEP 683.
If an object is immortal, its reference count is never modified, and therefore it is never deallocated while the
interpreter is running. For example, True and None are immortal in CPython.
immutable
An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot
65
Python Setup and Usage, Release 3.12.9
be altered. A new object has to be created if a different value has to be stored. They play an important role in
places where a constant hash value is needed, for example as a key in a dictionary.
import path
A list of locations (or path entries) that are searched by the path based finder for modules to import. During
import, this list of locations usually comes from sys.path, but for subpackages it may also come from the
parent package’s __path__ attribute.
importing
The process by which Python code in one module is made available to Python code in another module.
importer
An object that both finds and loads a module; both a finder and loader object.
interactive
Python has an interactive interpreter which means you can enter statements and expressions at the interpreter
prompt, immediately execute them and see their results. Just launch python with no arguments (possibly
by selecting it from your computer’s main menu). It is a very powerful way to test out new ideas or inspect
modules and packages (remember help(x)).
interpreted
Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because
of the presence of the bytecode compiler. This means that source files can be run directly without explicitly
creating an executable which is then run. Interpreted languages typically have a shorter development/debug
cycle than compiled ones, though their programs generally also run more slowly. See also interactive.
interpreter shutdown
When asked to shut down, the Python interpreter enters a special phase where it gradually releases all allocated
resources, such as modules and various critical internal structures. It also makes several calls to the garbage
collector. This can trigger the execution of code in user-defined destructors or weakref callbacks. Code exe-
cuted during the shutdown phase can encounter various exceptions as the resources it relies on may not function
anymore (common examples are library modules or the warnings machinery).
The main reason for interpreter shutdown is that the __main__ module or the script being run has finished
executing.
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types
(such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any
classes you define with an __iter__() method or with a __getitem__() method that implements sequence
semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(),
…). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator
for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not
necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for
you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator,
sequence, and generator.
iterator
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing
it to the built-in function next()) return successive items in the stream. When no more data are available a
StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls
to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places
where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A
container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function
or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used
in the previous iteration pass, making it appear like an empty container.
More information can be found in typeiter.
CPython implementation detail: CPython does not consistently apply the requirement that an iterator define
__iter__().
66 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
key function
A key function or collation function is a callable that returns a value used for sorting or ordering. For example,
locale.strxfrm() is used to produce a sort key that is aware of locale specific sort conventions.
A number of tools in Python accept key functions to control how elements are ordered or grouped. They
include min(), max(), sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.
nlargest(), and itertools.groupby().
There are several ways to create a key function. For example. the str.lower() method can serve as a
key function for case insensitive sorts. Alternatively, a key function can be built from a lambda expression
such as lambda r: (r[0], r[2]). Also, operator.attrgetter(), operator.itemgetter(), and
operator.methodcaller() are three key function constructors. See the Sorting HOW TO for examples
of how to create and use key functions.
keyword argument
See argument.
lambda
An anonymous inline function consisting of a single expression which is evaluated when the function is called.
The syntax to create a lambda function is lambda [parameters]: expression
LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This
style contrasts with the EAFP approach and is characterized by the presence of many if statements.
In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the
looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can
fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved
with locks or by using the EAFP approach.
lexical analyzer
Formal name for the tokenizer; see token.
list
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list
since access to elements is O(1).
list comprehension
A compact way to process all or part of the elements in a sequence and return a list with the results. result
= ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] generates a list of strings con-
taining even hex numbers (0x..) in the range from 0 to 255. The if clause is optional. If omitted, all elements
in range(256) are processed.
loader
An object that loads a module. It must define the exec_module() and create_module() methods to
implement the Loader interface. A loader is typically returned by a finder. See also:
• finders-and-loaders
• importlib.abc.Loader
• PEP 302
locale encoding
On Unix, it is the encoding of the LC_CTYPE locale. It can be set with locale.setlocale(locale.
LC_CTYPE, new_locale).
On Windows, it is the ANSI code page (ex: "cp1252").
On Android and VxWorks, Python uses "utf-8" as the locale encoding.
locale.getencoding() can be used to get the locale encoding.
67
Python Setup and Usage, Release 3.12.9
mapping
A container object that supports arbitrary key lookups and implements the methods specified in the
collections.abc.Mapping or collections.abc.MutableMapping abstract base classes. Exam-
ples include dict, collections.defaultdict, collections.OrderedDict and collections.
Counter.
Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be
created from a regular class definition that inherits from tuple and that defines named fields. Such a class
can be written by hand, or it can be created by inheriting typing.NamedTuple, or with the factory function
68 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
collections.namedtuple(). The latter techniques also add some extra methods that may not be found
in hand-written or built-in named tuples.
namespace
The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local,
global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support
modularity by preventing naming conflicts. For instance, the functions builtins.open and os.open() are
distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear
which module implements a function. For instance, writing random.seed() or itertools.islice()
makes it clear that those functions are implemented by the random and itertools modules, respectively.
namespace package
A package which serves only as a container for subpackages. Namespace packages may have no physical
representation, and specifically are not like a regular package because they have no __init__.py file.
Namespace packages allow several individually installable packages to have a common parent package. Oth-
erwise, it is recommended to use a regular package.
For more information, see PEP 420 and reference-namespace-package.
See also module.
nested scope
The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another
function can refer to variables in the outer function. Note that nested scopes by default work only for reference
and not for assignment. Local variables both read and write in the innermost scope. Likewise, global variables
read and write to the global namespace. The nonlocal allows writing to outer scopes.
new-style class
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only
new-style classes could use Python’s newer, versatile features like __slots__, descriptors, properties,
__getattribute__(), class methods, and static methods.
object
Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any
new-style class.
package
A Python module which can contain submodules or recursively, subpackages. Technically, a package is a
Python module with a __path__ attribute.
See also regular package and namespace package.
parameter
A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments)
that the function can accept. There are five kinds of parameter:
• positional-or-keyword: specifies an argument that can be passed either positionally or as a keyword argu-
ment. This is the default kind of parameter, for example foo and bar in the following:
• positional-only: specifies an argument that can be supplied only by position. Positional-only parameters
can be defined by including a / character in the parameter list of the function definition after them, for
example posonly1 and posonly2 in the following:
• keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters
can be defined by including a single var-positional parameter or bare * in the parameter list of the function
definition before them, for example kw_only1 and kw_only2 in the following:
69
Python Setup and Usage, Release 3.12.9
• var-positional: specifies that an arbitrary sequence of positional arguments can be provided (in addition
to any positional arguments already accepted by other parameters). Such a parameter can be defined by
prepending the parameter name with *, for example args in the following:
• var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any key-
word arguments already accepted by other parameters). Such a parameter can be defined by prepending
the parameter name with **, for example kwargs in the example above.
Parameters can specify both optional and required arguments, as well as default values for some optional
arguments.
See also the argument glossary entry, the FAQ question on the difference between arguments and parameters,
the inspect.Parameter class, the function section, and PEP 362.
path entry
A single location on the import path which the path based finder consults to find modules for importing.
path entry finder
A finder returned by a callable on sys.path_hooks (i.e. a path entry hook) which knows how to locate
modules given a path entry.
See importlib.abc.PathEntryFinder for the methods that path entry finders implement.
path entry hook
A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules on
a specific path entry.
path based finder
One of the default meta path finders which searches an import path for modules.
path-like object
An object representing a file system path. A path-like object is either a str or bytes object representing
a path, or an object implementing the os.PathLike protocol. An object that supports the os.PathLike
protocol can be converted to a str or bytes file system path by calling the os.fspath() function; os.
fsdecode() and os.fsencode() can be used to guarantee a str or bytes result instead, respectively.
Introduced by PEP 519.
PEP
Python Enhancement Proposal. A PEP is a design document providing information to the Python community,
or describing a new feature for Python or its processes or environment. PEPs should provide a concise technical
specification and a rationale for proposed features.
PEPs are intended to be the primary mechanisms for proposing major new features, for collecting community
input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is
responsible for building consensus within the community and documenting dissenting opinions.
See PEP 1.
portion
A set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package, as
defined in PEP 420.
positional argument
See argument.
provisional API
A provisional API is one which has been deliberately excluded from the standard library’s backwards com-
patibility guarantees. While major changes to such interfaces are not expected, as long as they are marked
provisional, backwards incompatible changes (up to and including removal of the interface) may occur if
deemed necessary by core developers. Such changes will not be made gratuitously – they will occur only if
serious fundamental flaws are uncovered that were missed prior to the inclusion of the API.
Even for provisional APIs, backwards incompatible changes are seen as a “solution of last resort” - every
attempt will still be made to find a backwards compatible resolution to any identified problems.
70 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
This process allows the standard library to continue to evolve over time, without locking in problematic design
errors for extended periods of time. See PEP 411 for more details.
provisional package
See provisional API.
Python 3000
Nickname for the Python 3.x release line (coined long ago when the release of version 3 was something in the
distant future.) This is also abbreviated “Py3k”.
Pythonic
An idea or piece of code which closely follows the most common idioms of the Python language, rather than
implementing code using concepts common to other languages. For example, a common idiom in Python is
to loop over all elements of an iterable using a for statement. Many other languages don’t have this type of
construct, so people unfamiliar with Python sometimes use a numerical counter instead:
for i in range(len(food)):
print(food[i])
qualified name
A dotted name showing the “path” from a module’s global scope to a class, function or method defined in that
module, as defined in PEP 3155. For top-level functions and classes, the qualified name is the same as the
object’s name:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
When used to refer to modules, the fully qualified name means the entire dotted path to the module, including
any parent packages, e.g. email.mime.text:
reference count
The number of references to an object. When the reference count of an object drops to zero, it is deallocated.
Some objects are “immortal” and have reference counts that are never modified, and therefore the objects are
never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the
CPython implementation. Programmers can call the sys.getrefcount() function to return the reference
count for a particular object.
regular package
A traditional package, such as a directory containing an __init__.py file.
See also namespace package.
__slots__
A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating
71
Python Setup and Usage, Release 3.12.9
instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for
rare cases where there are large numbers of instances in a memory-critical application.
sequence
An iterable which supports efficient element access using integer indices via the __getitem__() special
method and defines a __len__() method that returns the length of the sequence. Some built-in sequence
types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(),
but is considered a mapping rather than a sequence because the lookups use arbitrary hashable keys rather
than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes beyond just
__getitem__() and __len__(), adding count(), index(), __contains__(), and __reversed__().
Types that implement this expanded interface can be registered explicitly using register(). For more
documentation on sequence methods generally, see Common Sequence Operations.
set comprehension
A compact way to process all or part of the elements in an iterable and return a set with the results. results
= {c for c in 'abracadabra' if c not in 'abc'} generates the set of strings {'r', 'd'}. See
comprehensions.
single dispatch
A form of generic function dispatch where the implementation is chosen based on the type of a single argument.
slice
An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with
colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (sub-
script) notation uses slice objects internally.
soft deprecated
A soft deprecated API should not be used in new code, but it is safe for already existing code to use it. The
API remains documented and tested, but will not be enhanced further.
Soft deprecation, unlike normal deprecation, does not plan on removing the API and will not emit warnings.
See PEP 387: Soft Deprecation.
special method
A method that is called implicitly by Python to execute a certain operation on a type, such as addition. Such
methods have names starting and ending with double underscores. Special methods are documented in spe-
cialnames.
statement
A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs
with a keyword, such as if, while or for.
static type checker
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also
type hints and the typing module.
strong reference
In Python’s C API, a strong reference is a reference to an object which is owned by the code holding the
reference. The strong reference is taken by calling Py_INCREF() when the reference is created and released
with Py_DECREF() when the reference is deleted.
The Py_NewRef() function can be used to create a strong reference to an object. Usually, the Py_DECREF()
function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking
one reference.
See also borrowed reference.
text encoding
A string in Python is a sequence of Unicode code points (in range U+0000–U+10FFFF). To store or transfer
a string, it needs to be serialized as a sequence of bytes.
Serializing a string into a sequence of bytes is known as “encoding”, and recreating the string from the sequence
of bytes is known as “decoding”.
72 Appendix A. Glossary
Python Setup and Usage, Release 3.12.9
There are a variety of different text serialization codecs, which are collectively referred to as “text encodings”.
text file
A file object able to read and write str objects. Often, a text file actually accesses a byte-oriented datastream
and handles the text encoding automatically. Examples of text files are files opened in text mode ('r' or 'w'),
sys.stdin, sys.stdout, and instances of io.StringIO.
See also binary file for a file object able to read and write bytes-like objects.
token
A small unit of source code, generated by the lexical analyzer (also called the tokenizer). Names, numbers,
strings, operators, newlines and similar are represented by tokens.
The tokenize module exposes Python’s lexical analyzer. The token module contains information on the
various types of tokens.
triple-quoted string
A string which is bound by three instances of either a quotation mark (”) or an apostrophe (‘). While they don’t
provide any functionality not available with single-quoted strings, they are useful for a number of reasons.
They allow you to include unescaped single and double quotes within a string and they can span multiple lines
without the use of the continuation character, making them especially useful when writing docstrings.
type
The type of a Python object determines what kind of object it is; every object has a type. An object’s type is
accessible as its __class__ attribute or can be retrieved with type(obj).
type alias
A synonym for a type, created by assigning the type to an identifier.
Type aliases are useful for simplifying type hints. For example:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
73
Python Setup and Usage, Release 3.12.9
class C:
field: 'annotation'
Variable annotations are usually used for type hints: for example this variable is expected to take int values:
count: int = 0
74 Appendix A. Glossary
APPENDIX
Python’s documentation is generated from reStructuredText sources using Sphinx, a documentation generator origi-
nally created for Python and now maintained as an independent project.
Development of the documentation and its toolchain is an entirely volunteer effort, just like Python itself. If you
want to contribute, please take a look at the reporting-bugs page for information on how to do so. New volunteers
are always welcome!
Many thanks go to:
• Fred L. Drake, Jr., the creator of the original Python documentation toolset and author of much of the content;
• the Docutils project for creating reStructuredText and the Docutils suite;
• Fredrik Lundh for his Alternative Python Reference project from which Sphinx got many good ideas.
75
Python Setup and Usage, Release 3.12.9
® Note
(1) GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike
the GPL, let you distribute a modified version without making your changes open source. The GPL-
compatible licenses make it possible to combine Python with other software that is released under the
GPL; the others don’t.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause.
According to CNRI, however, Stallman’s lawyer has told CNRI’s lawyer that 1.6.1 is “not incompatible”
with the GPL.
Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases possible.
77
Python Setup and Usage, Release 3.12.9
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-2023 Python Software Foundation; All Rights
Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
(continues on next page)
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
(continues on next page)
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.2 Sockets
The socket module uses the functions, getaddrinfo(), and getnameinfo(), which are coded in separate source
files from the WIDE Project, https://www.wide.ad.jp/.
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.
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,
Bioreason or Mojam Media 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
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
The test.test_epoll module contains the following notice:
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.10 SipHash24
The file Python/pyhash.c contains Marek Majkowski’ implementation of Dan Bernstein’s SipHash24 algorithm.
It contains the following note:
<MIT License>
Copyright (c) 2013 Marek Majkowski <marek@popcount.org>
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>
Original location:
https://github.com/majek/csiphash/
/****************************************************************
*
* 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
The modules hashlib, posix, ssl, crypt use the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL
libraries, so we include a copy of the OpenSSL license here. For the OpenSSL 3.0 release, and later releases derived
from that, the Apache License v2 applies:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
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.
C.3.13 expat
The pyexpat extension is built using an included copy of the expat sources unless the build is configured
--with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
C.3.14 libffi
The _ctypes C extension underlying the ctypes module is built using an included copy of the libffi sources unless
the build is configured --with-system-libffi:
Copyright (c) 1996-2008 Red Hat, Inc and others.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
The zlib extension is built using an included copy of the zlib sources if the zlib version found on the system is too
old to be used for the build:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
(continues on next page)
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
C.3.16 cfuhash
The implementation of the hash table used by the tracemalloc is based on the cfuhash project:
Copyright (c) 2005 Don Owens
All rights reserved.
C.3.17 libmpdec
The _decimal C extension underlying the decimal module is built using an included copy of the libmpdec library
unless the build is configured --with-system-libmpdec:
Copyright (c) 2008-2020 Stefan Krah. All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.19 Audioop
The audioop module uses the code base in g771.c file of the SoX project. https://sourceforge.net/projects/sox/files/
sox/12.17.7/sox-12.17.7.tar.gz
This source code is a product of Sun Microsystems, Inc. and is provided for unrestricted use. Users may
copy or modify this source code without charge.
SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUD-
ING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICU-
LAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRAC-
TICE.
Sun source code is provided with no support and without any obligation on the part of Sun Microsystems,
Inc. to assist in its use, correction, modification or enhancement.
SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE IN-
FRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE
OR ANY PART THEREOF.
In no event will Sun Microsystems, Inc. be liable for any lost revenue or profits or other special, indirect
and consequential damages, even if Sun has been advised of the possibility of such damages.
Sun Microsystems, Inc. 2550 Garcia Avenue Mountain View, California 94043
C.3.20 asyncio
Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:
COPYRIGHT
See History and License for complete license and permissions information.
95
Python Setup and Usage, Release 3.12.9
96 Appendix D. Copyright
INDEX
97
Python Setup and Usage, Release 3.12.9
-v, 7 D
--version, 5 -d
-W, 7 command line option, 6
--with-address-sanitizer, 27 decorator, 62
--with-assertions, 26 descriptor, 62
--with-build-python, 29 dictionary, 62
--with-builtin-hashlib-hashes, 28 dictionary comprehension, 62
--with-computed-gotos, 25 dictionary view, 63
--with-dbmliborder, 22 --disable-ipv6
--with-dtrace, 27 command line option, 22
--with-emscripten-target, 23 --disable-test-modules
--with-ensurepip, 24 command line option, 24
--with-framework-name, 29 docstring, 63
--with-hash-algorithm, 28 duck-typing, 63
--with-libc, 27
--with-libm, 27 E
--with-libs, 27
-E
--with-lto, 25
command line option, 6
--with-memory-sanitizer, 27
EAFP, 63
--with-openssl, 28
--enable-big-digits
--with-openssl-rpath, 28
command line option, 22
--without-c-locale-coercion, 22
--enable-bolt
--without-decimal-contextvar, 22
command line option, 25
--without-doc-strings, 25
--enable-framework
--without-freelists, 23
command line option, 29
--without-pymalloc, 25
--enable-loadable-sqlite-extensions
--without-readline, 27
command line option, 22
--without-static-libpython, 27
--enable-optimizations
--with-pkg-config, 23
command line option, 24
--with-platlibdir, 23
--enable-profiling
--with-pydebug, 26
command line option, 25
--with-readline, 27
--enable-pystats
--with-ssl-default-suites, 28
command line option, 23
--with-strict-overflow, 25
--enable-shared
--with-suffix, 22
command line option, 27
--with-system-expat, 27
--enable-universalsdk
--with-system-libmpdec, 27
command line option, 29
--with-trace-refs, 26
--enable-wasm-dynamic-linking
--with-tzpath, 22
command line option, 23
--with-undefined-behavior-sanitizer,
--enable-wasm-pthreads
27
command line option, 23
--with-universal-archs, 29
environment variable
--with-valgrind, 26
%APPDATA%, 40
--with-wheel-pkg-dir, 23
BASECFLAGS, 32
-X, 8
BASECPPFLAGS, 31
-x, 8
BLDSHARED, 34
complex number, 61
CC, 32
CONFIG_SITE
CCSHARED, 32
command line option, 29
CFLAGS, 24, 32, 33
context manager, 61
CFLAGS_ALIASING, 32
context variable, 62
CFLAGS_NODIST, 32, 33
contiguous, 62
CFLAGSFORSHARED, 32
coroutine, 62
COMPILEALL_OPTS, 32
coroutine function, 62
CONFIGURE_CFLAGS, 32
CPPFLAGS, 31, 33
CONFIGURE_CFLAGS_NODIST, 32
CPython, 62
CONFIGURE_CPPFLAGS, 31
CONFIGURE_LDFLAGS, 33
CONFIGURE_LDFLAGS_NODIST, 33
98 Index
Python Setup and Usage, Release 3.12.9
Index 99
Python Setup and Usage, Release 3.12.9
100 Index
Python Setup and Usage, Release 3.12.9
Index 101
Python Setup and Usage, Release 3.12.9
X
-X
102 Index