Remote debugging attachment protocol

Remote debugging attachment protocol¶
This protocol enables external tools to attach to a running CPython process and execute Python code remotely.
Most platforms require elevated privileges to attach to another Python process.
Disabling remote debugging¶
To disable remote debugging support, use any of the following:
Set the
PYTHON_DISABLE_REMOTE_DEBUG
environment variable to1
before starting the interpreter.Use the
-X disable_remote_debug
command-line option.Compile Python with the
--without-remote-debug
build flag.
Permission requirements¶
Attaching to a running Python process for remote debugging requires elevated privileges on most platforms. The specific requirements and troubleshooting steps depend on your operating system:
Linux
The tracer process must have the CAP_SYS_PTRACE
capability or equivalent
privileges. You can only trace processes you own and can signal. Tracing may
fail if the process is already being traced, or if it is running with
set-user-ID or set-group-ID. Security modules like Yama may further restrict
tracing.
To temporarily relax ptrace restrictions (until reboot), run:
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
Note
Disabling ptrace_scope
reduces system hardening and should only be done
in trusted environments.
If running inside a container, use --cap-add=SYS_PTRACE
or
--privileged
, and run as root if needed.
Try re-running the command with elevated privileges:
sudo -E !!
macOS
To attach to another process, you typically need to run your debugging tool
with elevated privileges. This can be done by using sudo
or running as
root.
Even when attaching to processes you own, macOS may block debugging unless the debugger is run with root privileges due to system security restrictions.
Windows
To attach to another process, you usually need to run your debugging tool with administrative privileges. Start the command prompt or terminal as Administrator.
Some processes may still be inaccessible even with Administrator rights,
unless you have the SeDebugPrivilege
privilege enabled.
To resolve file or folder access issues, adjust the security permissions:
Right-click the file or folder and select Properties.
Go to the Security tab to view users and groups with access.
Click Edit to modify permissions.
Select your user account.
In Permissions, check Read or Full control as needed.
Click Apply, then OK to confirm.
Note
Ensure you’ve satisfied all Permission requirements before proceeding.
This section describes the low-level protocol that enables external tools to inject and execute a Python script within a running CPython process.
This mechanism forms the basis of the sys.remote_exec()
function, which
instructs a remote Python process to execute a .py
file. However, this
section does not document the usage of that function. Instead, it provides a
detailed explanation of the underlying protocol, which takes as input the
pid
of a target Python process and the path to a Python source file to be
executed. This information supports independent reimplementation of the
protocol, regardless of programming language.
Warning
The execution of the injected script depends on the interpreter reaching a safe evaluation point. As a result, execution may be delayed depending on the runtime state of the target process.
Once injected, the script is executed by the interpreter within the target process the next time a safe evaluation point is reached. This approach enables remote execution capabilities without modifying the behavior or structure of the running Python application.
Subsequent sections provide a step-by-step description of the protocol, including techniques for locating interpreter structures in memory, safely accessing internal fields, and triggering code execution. Platform-specific variations are noted where applicable, and example implementations are included to clarify each operation.
Locating the PyRuntime structure¶
CPython places the PyRuntime
structure in a dedicated binary section to
help external tools find it at runtime. The name and format of this section
vary by platform. For example, .PyRuntime
is used on ELF systems, and
__DATA,__PyRuntime
is used on macOS. Tools can find the offset of this
structure by examining the binary on disk.
The PyRuntime
structure contains CPython’s global interpreter state and
provides access to other internal data, including the list of interpreters,
thread states, and debugger support fields.
To work with a remote Python process, a debugger must first find the memory
address of the PyRuntime
structure in the target process. This address
can’t be hardcoded or calculated from a symbol name, because it depends on
where the operating system loaded the binary.
The method for finding PyRuntime
depends on the platform, but the steps are
the same in general:
Find the base address where the Python binary or shared library was loaded in the target process.
Use the on-disk binary to locate the offset of the
.PyRuntime
section.Add the section offset to the base address to compute the address in memory.
The sections below explain how to do this on each supported platform and include example code.
Linux (ELF)
To find the PyRuntime
structure on Linux:
Read the process’s memory map (for example,
/proc/<pid>/maps
) to find the address where the Python executable orlibpython
was loaded.Parse the ELF section headers in the binary to get the offset of the
.PyRuntime
section.Add that offset to the base address from step 1 to get the memory address of
PyRuntime
.
The following is an example implementation:
def find_py_runtime_linux(pid: int) -> int:
# Step 1: Try to find the Python executable in memory
binary_path, base_address = find_mapped_binary(
pid, name_contains="python"
)
# Step 2: Fallback to shared library if executable is not found
if binary_path is None:
binary_path, base_address = find_mapped_binary(
pid, name_contains="libpython"
)
# Step 3: Parse ELF headers to get .PyRuntime section offset
section_offset = parse_elf_section_offset(
binary_path, ".PyRuntime"
)
# Step 4: Compute PyRuntime address in memory
return base_address + section_offset
On Linux systems, there are two main approaches to read memory from another
process. The first is through the /proc
filesystem, specifically by reading from
/proc/[pid]/mem
which provides direct access to the process’s memory. This
requires appropriate permissions - either being the same user as the target
process or having root access. The second approach is using the
process_vm_readv()
system call which provides a more efficient way to copy
memory between processes. While ptrace’s PTRACE_PEEKTEXT
operation can also be
used to read memory, it is significantly slower as it only reads one word at a
time and requires multiple context switches between the tracer and tracee
processes.
For parsing ELF sections, the process involves reading and interpreting the ELF file format structures from the binary file on disk. The ELF header contains a pointer to the section header table. Each section header contains metadata about a section including its name (stored in a separate string table), offset, and size. To find a specific section like .PyRuntime, you need to walk through these headers and match the section name. The section header then provides the offset where that section exists in the file, which can be used to calculate its runtime address when the binary is loaded into memory.
You can read more about the ELF file format in the ELF specification.
macOS (Mach-O)
To find the PyRuntime
structure on macOS:
Call
task_for_pid()
to get themach_port_t
task port for the target process. This handle is needed to read memory using APIs likemach_vm_read_overwrite
andmach_vm_region
.Scan the memory regions to find the one containing the Python executable or
libpython
.Load the binary file from disk and parse the Mach-O headers to find the section named
PyRuntime
in the__DATA
segment. On macOS, symbol names are automatically prefixed with an underscore, so thePyRuntime
symbol appears as_PyRuntime
in the symbol table, but the section name is not affected.
The following is an example implementation:
def find_py_runtime_macos(pid: int) -> int:
# Step 1: Get access to the process's memory
handle = get_memory_access_handle(pid)
# Step 2: Try to find the Python executable in memory
binary_path, base_address = find_mapped_binary(
handle, name_contains="python"
)
# Step 3: Fallback to libpython if the executable is not found
if binary_path is None:
binary_path, base_address = find_mapped_binary(
handle, name_contains="libpython"
)
# Step 4: Parse Mach-O headers to get __DATA,__PyRuntime section offset
section_offset = parse_macho_section_offset(
binary_path, "__DATA", "__PyRuntime"
)
# Step 5: Compute the PyRuntime address in memory
return base_address + section_offset
On macOS, accessing another process’s memory requires using Mach-O specific APIs
and file formats. The first step is obtaining a task_port
handle via
task_for_pid()
, which provides access to the target process’s memory space.
This handle enables memory operations through APIs like
mach_vm_read_overwrite()
.
The process memory can be examined using mach_vm_region()
to scan through the
virtual memory space, while proc_regionfilename()
helps identify which binary
files are loaded at each memory region. When the Python binary or library is
found, its Mach-O headers need to be parsed to locate the PyRuntime
structure.
The Mach-O format organizes code and data into segments and sections. The
PyRuntime
structure lives in a section named __PyRuntime
within the
__DATA
segment. The actual runtime address calculation involves finding the
__TEXT
segment which serves as the binary’s base address, then locating the
__DATA
segment containing our target section. The final address is computed by
combining the base address with the appropriate section offsets from the Mach-O
headers.
Note that accessing another process’s memory on macOS typically requires elevated privileges - either root access or special security entitlements granted to the debugging process.
Windows (PE)
To find the PyRuntime
structure on Windows:
Use the ToolHelp API to enumerate all modules loaded in the target process. This is done using functions such as CreateToolhelp32Snapshot, Module32First, and Module32Next.
Identify the module corresponding to
python.exe
orpythonXY.dll
, whereX
andY
are the major and minor version numbers of the Python version, and record its base address.Locate the
PyRuntim
section. Due to the PE format’s 8-character limit on section names (defined asIMAGE_SIZEOF_SHORT_NAME
), the original namePyRuntime
is truncated. This section contains thePyRuntime
structure.Retrieve the section’s relative virtual address (RVA) and add it to the base address of the module.
The following is an example implementation:
def find_py_runtime_windows(pid: int) -> int:
# Step 1: Try to find the Python executable in memory
binary_path, base_address = find_loaded_module(
pid, name_contains="python"
)
# Step 2: Fallback to shared pythonXY.dll if the executable is not
# found
if binary_path is None:
binary_path, base_address = find_loaded_module(
pid, name_contains="python3"
)
# Step 3: Parse PE section headers to get the RVA of the PyRuntime
# section. The section name appears as "PyRuntim" due to the
# 8-character limit defined by the PE format (IMAGE_SIZEOF_SHORT_NAME).
section_rva = parse_pe_section_offset(binary_path, "PyRuntim")
# Step 4: Compute PyRuntime address in memory
return base_address + section_rva
On Windows, accessing another process’s memory requires using the Windows API
functions like CreateToolhelp32Snapshot()
and Module32First()/Module32Next()
to enumerate loaded modules. The OpenProcess()
function provides a handle to
access the target process’s memory space, enabling memory operations through
ReadProcessMemory()
.
The process memory can be examined by enumerating loaded modules to find the
Python binary or DLL. When found, its PE headers need to be parsed to locate the
PyRuntime
structure.
The PE format organizes code and data into sections. The PyRuntime
structure
lives in a section named “PyRuntim” (truncated from “PyRuntime” due to PE’s
8-character name limit). The actual runtime address calculation involves finding
the module’s base address from the module entry, then locating our target
section in the PE headers. The final address is computed by combining the base
address with the section’s virtual address from the PE section headers.
Note that accessing another process’s memory on Windows typically requires
appropriate privileges - either administrative access or the SeDebugPrivilege
privilege granted to the debugging process.
Reading _Py_DebugOffsets¶
Once the address of the PyRuntime
structure has been determined, the next
step is to read the _Py_DebugOffsets
structure located at the beginning of
the PyRuntime
block.
This structure provides version-specific field offsets that are needed to safely read interpreter and thread state memory. These offsets vary between CPython versions and must be checked before use to ensure they are compatible.
To read and check the debug offsets, follow these steps:
Read memory from the target process starting at the
PyRuntime
address, covering the same number of bytes as the_Py_DebugOffsets
structure. This structure is located at the very start of thePyRuntime
memory block. Its layout is defined in CPython’s internal headers and stays the same within a given minor version, but may change in major versions.Check that the structure contains valid data:
The
cookie
field must match the expected debug marker.The
version
field must match the version of the Python interpreter used by the debugger.If either the debugger or the target process is using a pre-release version (for example, an alpha, beta, or release candidate), the versions must match exactly.
The
free_threaded
field must have the same value in both the debugger and the target process.
If the structure is valid, the offsets it contains can be used to locate fields in memory. If any check fails, the debugger should stop the operation to avoid reading memory in the wrong format.
The following is an example implementation that reads and checks
_Py_DebugOffsets
:
def read_debug_offsets(pid: int, py_runtime_addr: int) -> DebugOffsets:
# Step 1: Read memory from the target process at the PyRuntime address
data = read_process_memory(
pid, address=py_runtime_addr, size=DEBUG_OFFSETS_SIZE
)
# Step 2: Deserialize the raw bytes into a _Py_DebugOffsets structure
debug_offsets = parse_debug_offsets(data)
# Step 3: Validate the contents of the structure
if debug_offsets.cookie != EXPECTED_COOKIE:
raise RuntimeError("Invalid or missing debug cookie")
if debug_offsets.version != LOCAL_PYTHON_VERSION:
raise RuntimeError(
"Mismatch between caller and target Python versions"
)
if debug_offsets.free_threaded != LOCAL_FREE_THREADED:
raise RuntimeError("Mismatch in free-threaded configuration")
return debug_offsets
Warning
Process suspension recommended
To avoid race conditions and ensure memory consistency, it is strongly recommended that the target process be suspended before performing any operations that read or write internal interpreter state. The Python runtime may concurrently mutate interpreter data structures—such as creating or destroying threads—during normal execution. This can result in invalid memory reads or writes.
A debugger may suspend execution by attaching to the process with ptrace
or by sending a SIGSTOP
signal. Execution should only be resumed after
debugger-side memory operations are complete.
Note
Some tools, such as profilers or sampling-based debuggers, may operate on a running process without suspension. In such cases, tools must be explicitly designed to handle partially updated or inconsistent memory. For most debugger implementations, suspending the process remains the safest and most robust approach.
Locating the interpreter and thread state¶
Before code can be injected and executed in a remote Python process, the
debugger must choose a thread in which to schedule execution. This is necessary
because the control fields used to perform remote code injection are located in
the _PyRemoteDebuggerSupport
structure, which is embedded in a
PyThreadState
object. These fields are modified by the debugger to request
execution of injected scripts.
The PyThreadState
structure represents a thread running inside a Python
interpreter. It maintains the thread’s evaluation context and contains the
fields required for debugger coordination. Locating a valid PyThreadState
is therefore a key prerequisite for triggering execution remotely.
A thread is typically selected based on its role or ID. In most cases, the main thread is used, but some tools may target a specific thread by its native thread ID. Once the target thread is chosen, the debugger must locate both the interpreter and the associated thread state structures in memory.
The relevant internal structures are defined as follows:
PyInterpreterState
represents an isolated Python interpreter instance. Each interpreter maintains its own set of imported modules, built-in state, and thread state list. Although most Python applications use a single interpreter, CPython supports multiple interpreters in the same process.PyThreadState
represents a thread running within an interpreter. It contains execution state and the control fields used by the debugger.
To locate a thread:
Use the offset
runtime_state.interpreters_head
to obtain the address of the first interpreter in thePyRuntime
structure. This is the entry point to the linked list of active interpreters.Use the offset
interpreter_state.threads_main
to access the main thread state associated with the selected interpreter. This is typically the most reliable thread to target.Optionally, use the offset
interpreter_state.threads_head
to iterate through the linked list of all thread states. EachPyThreadState
structure contains anative_thread_id
field, which may be compared to a target thread ID to find a specific thread.Once a valid
PyThreadState
has been found, its address can be used in later steps of the protocol, such as writing debugger control fields and scheduling execution.
The following is an example implementation that locates the main thread state:
def find_main_thread_state(
pid: int, py_runtime_addr: int, debug_offsets: DebugOffsets,
) -> int:
# Step 1: Read interpreters_head from PyRuntime
interp_head_ptr = (
py_runtime_addr + debug_offsets.runtime_state.interpreters_head
)
interp_addr = read_pointer(pid, interp_head_ptr)
if interp_addr == 0:
raise RuntimeError("No interpreter found in the target process")
# Step 2: Read the threads_main pointer from the interpreter
threads_main_ptr = (
interp_addr + debug_offsets.interpreter_state.threads_main
)
thread_state_addr = read_pointer(pid, threads_main_ptr)
if thread_state_addr == 0:
raise RuntimeError("Main thread state is not available")
return thread_state_addr
The following example demonstrates how to locate a thread by its native thread ID:
def find_thread_by_id(
pid: int,
interp_addr: int,
debug_offsets: DebugOffsets,
target_tid: int,
) -> int:
# Start at threads_head and walk the linked list
thread_ptr = read_pointer(
pid,
interp_addr + debug_offsets.interpreter_state.threads_head
)
while thread_ptr:
native_tid_ptr = (
thread_ptr + debug_offsets.thread_state.native_thread_id
)
native_tid = read_int(pid, native_tid_ptr)
if native_tid == target_tid:
return thread_ptr
thread_ptr = read_pointer(
pid,
thread_ptr + debug_offsets.thread_state.next
)
raise RuntimeError("Thread with the given ID was not found")
Once a valid thread state has been located, the debugger can proceed with modifying its control fields and scheduling execution, as described in the next section.
Writing control information¶
Once a valid PyThreadState
structure has been identified, the debugger may
modify control fields within it to schedule the execution of a specified Python
script. These control fields are checked periodically by the interpreter, and
when set correctly, they trigger the execution of remote code at a safe point
in the evaluation loop.
Each PyThreadState
contains a _PyRemoteDebuggerSupport
structure used
for communication between the debugger and the interpreter. The locations of
its fields are defined by the _Py_DebugOffsets
structure and include the
following:
debugger_script_path
: A fixed-size buffer that holds the full path to a Python source file (.py
). This file must be accessible and readable by the target process when execution is triggered.debugger_pending_call
: An integer flag. Setting this to1
tells the interpreter that a script is ready to be executed.eval_breaker
: A field checked by the interpreter during execution. Setting bit 5 (_PY_EVAL_PLEASE_STOP_BIT
, value1U << 5
) in this field causes the interpreter to pause and check for debugger activity.
To complete the injection, the debugger must perform the following steps:
Write the full script path into the
debugger_script_path
buffer.Set
debugger_pending_call
to1
.Read the current value of
eval_breaker
, set bit 5 (_PY_EVAL_PLEASE_STOP_BIT
), and write the updated value back. This signals the interpreter to check for debugger activity.
The following is an example implementation:
def inject_script(
pid: int,
thread_state_addr: int,
debug_offsets: DebugOffsets,
script_path: str
) -> None:
# Compute the base offset of _PyRemoteDebuggerSupport
support_base = (
thread_state_addr +
debug_offsets.debugger_support.remote_debugger_support
)
# Step 1: Write the script path into debugger_script_path
script_path_ptr = (
support_base +
debug_offsets.debugger_support.debugger_script_path
)
write_string(pid, script_path_ptr, script_path)
# Step 2: Set debugger_pending_call to 1
pending_ptr = (
support_base +
debug_offsets.debugger_support.debugger_pending_call
)
write_int(pid, pending_ptr, 1)
# Step 3: Set _PY_EVAL_PLEASE_STOP_BIT (bit 5, value 1 << 5) in
# eval_breaker
eval_breaker_ptr = (
thread_state_addr +
debug_offsets.debugger_support.eval_breaker
)
breaker = read_int(pid, eval_breaker_ptr)
breaker |= (1 << 5)
write_int(pid, eval_breaker_ptr, breaker)
Once these fields are set, the debugger may resume the process (if it was suspended). The interpreter will process the request at the next safe evaluation point, load the script from disk, and execute it.
It is the responsibility of the debugger to ensure that the script file remains present and accessible to the target process during execution.
Note
Script execution is asynchronous. The script file cannot be deleted immediately after injection. The debugger should wait until the injected script has produced an observable effect before removing the file. This effect depends on what the script is designed to do. For example, a debugger might wait until the remote process connects back to a socket before removing the script. Once such an effect is observed, it is safe to assume the file is no longer needed.
Summary¶
To inject and execute a Python script in a remote process:
Locate the
PyRuntime
structure in the target process’s memory.Read and validate the
_Py_DebugOffsets
structure at the beginning ofPyRuntime
.Use the offsets to locate a valid
PyThreadState
.Write the path to a Python script into
debugger_script_path
.Set the
debugger_pending_call
flag to1
.Set
_PY_EVAL_PLEASE_STOP_BIT
in theeval_breaker
field.Resume the process (if suspended). The script will execute at the next safe evaluation point.


Coroutines and Tasks

Coroutines and Tasks¶
This section outlines high-level asyncio APIs to work with coroutines and Tasks.
Coroutines¶
Source code: Lib/asyncio/coroutines.py
Coroutines declared with the async/await syntax is the preferred way of writing asyncio applications. For example, the following snippet of code prints “hello”, waits 1 second, and then prints “world”:
>>> import asyncio
>>> async def main():
... print('hello')
... await asyncio.sleep(1)
... print('world')
>>> asyncio.run(main())
hello
world
Note that simply calling a coroutine will not schedule it to be executed:
>>> main()
<coroutine object main at 0x1053bb7c8>
To actually run a coroutine, asyncio provides the following mechanisms:
The
asyncio.run()
function to run the top-level entry point “main()” function (see the above example.)Awaiting on a coroutine. The following snippet of code will print “hello” after waiting for 1 second, and then print “world” after waiting for another 2 seconds:
import asyncio import time async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print(f"started at {time.strftime('%X')}") await say_after(1, 'hello') await say_after(2, 'world') print(f"finished at {time.strftime('%X')}") asyncio.run(main())
Expected output:
started at 17:13:52 hello world finished at 17:13:55
The
asyncio.create_task()
function to run coroutines concurrently as asyncioTasks
.Let’s modify the above example and run two
say_after
coroutines concurrently:async def main(): task1 = asyncio.create_task( say_after(1, 'hello')) task2 = asyncio.create_task( say_after(2, 'world')) print(f"started at {time.strftime('%X')}") # Wait until both tasks are completed (should take # around 2 seconds.) await task1 await task2 print(f"finished at {time.strftime('%X')}")
Note that expected output now shows that the snippet runs 1 second faster than before:
started at 17:14:32 hello world finished at 17:14:34
The
asyncio.TaskGroup
class provides a more modern alternative tocreate_task()
. Using this API, the last example becomes:async def main(): async with asyncio.TaskGroup() as tg: task1 = tg.create_task( say_after(1, 'hello')) task2 = tg.create_task( say_after(2, 'world')) print(f"started at {time.strftime('%X')}") # The await is implicit when the context manager exits. print(f"finished at {time.strftime('%X')}")
The timing and output should be the same as for the previous version.
Added in version 3.11:
asyncio.TaskGroup
.
Awaitables¶
We say that an object is an awaitable object if it can be used
in an await
expression. Many asyncio APIs are designed to
accept awaitables.
There are three main types of awaitable objects: coroutines, Tasks, and Futures.
Coroutines
Python coroutines are awaitables and therefore can be awaited from other coroutines:
import asyncio
async def nested():
return 42
async def main():
# Nothing happens if we just call "nested()".
# A coroutine object is created but not awaited,
# so it *won't run at all*.
nested() # will raise a "RuntimeWarning".
# Let's do it differently now and await it:
print(await nested()) # will print "42".
asyncio.run(main())
Important
In this documentation the term “coroutine” can be used for two closely related concepts:
a coroutine function: an
async def
function;a coroutine object: an object returned by calling a coroutine function.
Tasks
Tasks are used to schedule coroutines concurrently.
When a coroutine is wrapped into a Task with functions like
asyncio.create_task()
the coroutine is automatically
scheduled to run soon:
import asyncio
async def nested():
return 42
async def main():
# Schedule nested() to run soon concurrently
# with "main()".
task = asyncio.create_task(nested())
# "task" can now be used to cancel "nested()", or
# can simply be awaited to wait until it is complete:
await task
asyncio.run(main())
Futures
A Future
is a special low-level awaitable object that
represents an eventual result of an asynchronous operation.
When a Future object is awaited it means that the coroutine will wait until the Future is resolved in some other place.
Future objects in asyncio are needed to allow callback-based code to be used with async/await.
Normally there is no need to create Future objects at the application level code.
Future objects, sometimes exposed by libraries and some asyncio APIs, can be awaited:
async def main():
await function_that_returns_a_future_object()
# this is also valid:
await asyncio.gather(
function_that_returns_a_future_object(),
some_python_coroutine()
)
A good example of a low-level function that returns a Future object
is loop.run_in_executor()
.
Creating Tasks¶
Source code: Lib/asyncio/tasks.py
- asyncio.create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)¶
Wrap the coro coroutine into a
Task
and schedule its execution. Return the Task object.The full function signature is largely the same as that of the
Task
constructor (or factory) - all of the keyword arguments to this function are passed through to that interface.An optional keyword-only context argument allows specifying a custom
contextvars.Context
for the coro to run in. The current context copy is created when no context is provided.An optional keyword-only eager_start argument allows specifying if the task should execute eagerly during the call to create_task, or be scheduled later. If eager_start is not passed the mode set by
loop.set_task_factory()
will be used.The task is executed in the loop returned by
get_running_loop()
,RuntimeError
is raised if there is no running loop in current thread.Note
asyncio.TaskGroup.create_task()
is a new alternative leveraging structural concurrency; it allows for waiting for a group of related tasks with strong safety guarantees.Important
Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:
background_tasks = set() for i in range(10): task = asyncio.create_task(some_coro(param=i)) # Add task to the set. This creates a strong reference. background_tasks.add(task) # To prevent keeping references to finished tasks forever, # make each task remove its own reference from the set after # completion: task.add_done_callback(background_tasks.discard)
Added in version 3.7.
Changed in version 3.8: Added the name parameter.
Changed in version 3.11: Added the context parameter.
Changed in version 3.14: Added the eager_start parameter by passing on all kwargs.
Task Cancellation¶
Tasks can easily and safely be cancelled.
When a task is cancelled, asyncio.CancelledError
will be raised
in the task at the next opportunity.
It is recommended that coroutines use try/finally
blocks to robustly
perform clean-up logic. In case asyncio.CancelledError
is explicitly caught, it should generally be propagated when
clean-up is complete. asyncio.CancelledError
directly subclasses
BaseException
so most code will not need to be aware of it.
The asyncio components that enable structured concurrency, like
asyncio.TaskGroup
and asyncio.timeout()
,
are implemented using cancellation internally and might misbehave if
a coroutine swallows asyncio.CancelledError
. Similarly, user code
should not generally call uncancel
.
However, in cases when suppressing asyncio.CancelledError
is
truly desired, it is necessary to also call uncancel()
to completely
remove the cancellation state.
Task Groups¶
Task groups combine a task creation API with a convenient and reliable way to wait for all tasks in the group to finish.
- class asyncio.TaskGroup¶
An asynchronous context manager holding a group of tasks. Tasks can be added to the group using
create_task()
. All tasks are awaited when the context manager exits.Added in version 3.11.
- create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)¶
Create a task in this task group. The signature matches that of
asyncio.create_task()
. If the task group is inactive (e.g. not yet entered, already finished, or in the process of shutting down), we will close the givencoro
.Changed in version 3.13: Close the given coroutine if the task group is not active.
Changed in version 3.14: Passes on all kwargs to
loop.create_task()
Example:
async def main():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(some_coro(...))
task2 = tg.create_task(another_coro(...))
print(f"Both tasks have completed now: {task1.result()}, {task2.result()}")
The async with
statement will wait for all tasks in the group to finish.
While waiting, new tasks may still be added to the group
(for example, by passing tg
into one of the coroutines
and calling tg.create_task()
in that coroutine).
Once the last task has finished and the async with
block is exited,
no new tasks may be added to the group.
The first time any of the tasks belonging to the group fails
with an exception other than asyncio.CancelledError
,
the remaining tasks in the group are cancelled.
No further tasks can then be added to the group.
At this point, if the body of the async with
statement is still active
(i.e., __aexit__()
hasn’t been called yet),
the task directly containing the async with
statement is also cancelled.
The resulting asyncio.CancelledError
will interrupt an await
,
but it will not bubble out of the containing async with
statement.
Once all tasks have finished, if any tasks have failed
with an exception other than asyncio.CancelledError
,
those exceptions are combined in an
ExceptionGroup
or BaseExceptionGroup
(as appropriate; see their documentation)
which is then raised.
Two base exceptions are treated specially:
If any task fails with KeyboardInterrupt
or SystemExit
,
the task group still cancels the remaining tasks and waits for them,
but then the initial KeyboardInterrupt
or SystemExit
is re-raised instead of ExceptionGroup
or BaseExceptionGroup
.
If the body of the async with
statement exits with an exception
(so __aexit__()
is called with an exception set),
this is treated the same as if one of the tasks failed:
the remaining tasks are cancelled and then waited for,
and non-cancellation exceptions are grouped into an
exception group and raised.
The exception passed into __aexit__()
,
unless it is asyncio.CancelledError
,
is also included in the exception group.
The same special case is made for
KeyboardInterrupt
and SystemExit
as in the previous paragraph.
Task groups are careful not to mix up the internal cancellation used to
“wake up” their __aexit__()
with cancellation requests
for the task in which they are running made by other parties.
In particular, when one task group is syntactically nested in another,
and both experience an exception in one of their child tasks simultaneously,
the inner task group will process its exceptions, and then the outer task group
will receive another cancellation and process its own exceptions.
In the case where a task group is cancelled externally and also must
raise an ExceptionGroup
, it will call the parent task’s
cancel()
method. This ensures that a
asyncio.CancelledError
will be raised at the next
await
, so the cancellation is not lost.
Task groups preserve the cancellation count
reported by asyncio.Task.cancelling()
.
Changed in version 3.13: Improved handling of simultaneous internal and external cancellations and correct preservation of cancellation counts.
Terminating a Task Group¶
While terminating a task group is not natively supported by the standard library, termination can be achieved by adding an exception-raising task to the task group and ignoring the raised exception:
import asyncio
from asyncio import TaskGroup
class TerminateTaskGroup(Exception):
"""Exception raised to terminate a task group."""
async def force_terminate_task_group():
"""Used to force termination of a task group."""
raise TerminateTaskGroup()
async def job(task_id, sleep_time):
print(f'Task {task_id}: start')
await asyncio.sleep(sleep_time)
print(f'Task {task_id}: done')
async def main():
try:
async with TaskGroup() as group:
# spawn some tasks
group.create_task(job(1, 0.5))
group.create_task(job(2, 1.5))
# sleep for 1 second
await asyncio.sleep(1)
# add an exception-raising task to force the group to terminate
group.create_task(force_terminate_task_group())
except* TerminateTaskGroup:
pass
asyncio.run(main())
Expected output:
Task 1: start
Task 2: start
Task 1: done
Sleeping¶
- async asyncio.sleep(delay, result=None)¶
Block for delay seconds.
If result is provided, it is returned to the caller when the coroutine completes.
sleep()
always suspends the current task, allowing other tasks to run.Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
import asyncio import datetime async def display_date(): loop = asyncio.get_running_loop() end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break await asyncio.sleep(1) asyncio.run(display_date())
Changed in version 3.10: Removed the loop parameter.
Changed in version 3.13: Raises
ValueError
if delay isnan
.
Running Tasks Concurrently¶
- awaitable asyncio.gather(*aws, return_exceptions=False)¶
Run awaitable objects in the aws sequence concurrently.
If any awaitable in aws is a coroutine, it is automatically scheduled as a Task.
If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.
If return_exceptions is
False
(default), the first raised exception is immediately propagated to the task that awaits ongather()
. Other awaitables in the aws sequence won’t be cancelled and will continue to run.If return_exceptions is
True
, exceptions are treated the same as successful results, and aggregated in the result list.If
gather()
is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.If any Task or Future from the aws sequence is cancelled, it is treated as if it raised
CancelledError
– thegather()
call is not cancelled in this case. This is to prevent the cancellation of one submitted Task/Future to cause other Tasks/Futures to be cancelled.Note
A new alternative to create and run tasks concurrently and wait for their completion is
asyncio.TaskGroup
. TaskGroup provides stronger safety guarantees than gather for scheduling a nesting of subtasks: if a task (or a subtask, a task scheduled by a task) raises an exception, TaskGroup will, while gather will not, cancel the remaining scheduled tasks).Example:
import asyncio async def factorial(name, number): f = 1 for i in range(2, number + 1): print(f"Task {name}: Compute factorial({number}), currently i={i}...") await asyncio.sleep(1) f *= i print(f"Task {name}: factorial({number}) = {f}") return f async def main(): # Schedule three calls *concurrently*: L = await asyncio.gather( factorial("A", 2), factorial("B", 3), factorial("C", 4), ) print(L) asyncio.run(main()) # Expected output: # # Task A: Compute factorial(2), currently i=2... # Task B: Compute factorial(3), currently i=2... # Task C: Compute factorial(4), currently i=2... # Task A: factorial(2) = 2 # Task B: Compute factorial(3), currently i=3... # Task C: Compute factorial(4), currently i=3... # Task B: factorial(3) = 6 # Task C: Compute factorial(4), currently i=4... # Task C: factorial(4) = 24 # [2, 6, 24]
Note
If return_exceptions is false, cancelling gather() after it has been marked done won’t cancel any submitted awaitables. For instance, gather can be marked done after propagating an exception to the caller, therefore, calling
gather.cancel()
after catching an exception (raised by one of the awaitables) from gather won’t cancel any other awaitables.Changed in version 3.7: If the gather itself is cancelled, the cancellation is propagated regardless of return_exceptions.
Changed in version 3.10: Removed the loop parameter.
Deprecated since version 3.10: Deprecation warning is emitted if no positional arguments are provided or not all positional arguments are Future-like objects and there is no running event loop.
Eager Task Factory¶
- asyncio.eager_task_factory(loop, coro, *, name=None, context=None)¶
A task factory for eager task execution.
When using this factory (via
loop.set_task_factory(asyncio.eager_task_factory)
), coroutines begin execution synchronously duringTask
construction. Tasks are only scheduled on the event loop if they block. This can be a performance improvement as the overhead of loop scheduling is avoided for coroutines that complete synchronously.A common example where this is beneficial is coroutines which employ caching or memoization to avoid actual I/O when possible.
Note
Immediate execution of the coroutine is a semantic change. If the coroutine returns or raises, the task is never scheduled to the event loop. If the coroutine execution blocks, the task is scheduled to the event loop. This change may introduce behavior changes to existing applications. For example, the application’s task execution order is likely to change.
Added in version 3.12.
- asyncio.create_eager_task_factory(custom_task_constructor)¶
Create an eager task factory, similar to
eager_task_factory()
, using the provided custom_task_constructor when creating a new task instead of the defaultTask
.custom_task_constructor must be a callable with the signature matching the signature of
Task.__init__
. The callable must return aasyncio.Task
-compatible object.This function returns a callable intended to be used as a task factory of an event loop via
loop.set_task_factory(factory)
).Added in version 3.12.
Shielding From Cancellation¶
- awaitable asyncio.shield(aw)¶
Protect an awaitable object from being
cancelled
.If aw is a coroutine it is automatically scheduled as a Task.
The statement:
task = asyncio.create_task(something()) res = await shield(task)
is equivalent to:
res = await something()
except that if the coroutine containing it is cancelled, the Task running in
something()
is not cancelled. From the point of view ofsomething()
, the cancellation did not happen. Although its caller is still cancelled, so the “await” expression still raises aCancelledError
.If
something()
is cancelled by other means (i.e. from within itself) that would also cancelshield()
.If it is desired to completely ignore cancellation (not recommended) the
shield()
function should be combined with a try/except clause, as follows:task = asyncio.create_task(something()) try: res = await shield(task) except CancelledError: res = None
Important
Save a reference to tasks passed to this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done.
Changed in version 3.10: Removed the loop parameter.
Deprecated since version 3.10: Deprecation warning is emitted if aw is not Future-like object and there is no running event loop.
Timeouts¶
- asyncio.timeout(delay)¶
Return an asynchronous context manager that can be used to limit the amount of time spent waiting on something.
delay can either be
None
, or a float/int number of seconds to wait. If delay isNone
, no time limit will be applied; this can be useful if the delay is unknown when the context manager is created.In either case, the context manager can be rescheduled after creation using
Timeout.reschedule()
.Example:
async def main(): async with asyncio.timeout(10): await long_running_task()
If
long_running_task
takes more than 10 seconds to complete, the context manager will cancel the current task and handle the resultingasyncio.CancelledError
internally, transforming it into aTimeoutError
which can be caught and handled.Note
The
asyncio.timeout()
context manager is what transforms theasyncio.CancelledError
into aTimeoutError
, which means theTimeoutError
can only be caught outside of the context manager.Example of catching
TimeoutError
:async def main(): try: async with asyncio.timeout(10): await long_running_task() except TimeoutError: print("The long operation timed out, but we've handled it.") print("This statement will run regardless.")
The context manager produced by
asyncio.timeout()
can be rescheduled to a different deadline and inspected.- class asyncio.Timeout(when)¶
An asynchronous context manager for cancelling overdue coroutines.
Prefer using
asyncio.timeout()
orasyncio.timeout_at()
rather than instantiatingTimeout
directly.when
should be an absolute time at which the context should time out, as measured by the event loop’s clock:If
when
isNone
, the timeout will never trigger.If
when < loop.time()
, the timeout will trigger on the next iteration of the event loop.
Example:
async def main(): try: # We do not know the timeout when starting, so we pass ``None``. async with asyncio.timeout(None) as cm: # We know the timeout now, so we reschedule it. new_deadline = get_running_loop().time() + 10 cm.reschedule(new_deadline) await long_running_task() except TimeoutError: pass if cm.expired(): print("Looks like we haven't finished on time.")
Timeout context managers can be safely nested.
Added in version 3.11.
- asyncio.timeout_at(when)¶
Similar to
asyncio.timeout()
, except when is the absolute time to stop waiting, orNone
.Example:
async def main(): loop = get_running_loop() deadline = loop.time() + 20 try: async with asyncio.timeout_at(deadline): await long_running_task() except TimeoutError: print("The long operation timed out, but we've handled it.") print("This statement will run regardless.")
Added in version 3.11.
- async asyncio.wait_for(aw, timeout)¶
Wait for the aw awaitable to complete with a timeout.
If aw is a coroutine it is automatically scheduled as a Task.
timeout can either be
None
or a float or int number of seconds to wait for. If timeout isNone
, block until the future completes.If a timeout occurs, it cancels the task and raises
TimeoutError
.To avoid the task
cancellation
, wrap it inshield()
.The function will wait until the future is actually cancelled, so the total wait time may exceed the timeout. If an exception happens during cancellation, it is propagated.
If the wait is cancelled, the future aw is also cancelled.
Example:
async def eternity(): # Sleep for one hour await asyncio.sleep(3600) print('yay!') async def main(): # Wait for at most 1 second try: await asyncio.wait_for(eternity(), timeout=1.0) except TimeoutError: print('timeout!') asyncio.run(main()) # Expected output: # # timeout!
Changed in version 3.7: When aw is cancelled due to a timeout,
wait_for
waits for aw to be cancelled. Previously, it raisedTimeoutError
immediately.Changed in version 3.10: Removed the loop parameter.
Changed in version 3.11: Raises
TimeoutError
instead ofasyncio.TimeoutError
.
Waiting Primitives¶
- async asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)¶
Run
Future
andTask
instances in the aws iterable concurrently and block until the condition specified by return_when.The aws iterable must not be empty.
Returns two sets of Tasks/Futures:
(done, pending)
.Usage:
done, pending = await asyncio.wait(aws)
timeout (a float or int), if specified, can be used to control the maximum number of seconds to wait before returning.
Note that this function does not raise
TimeoutError
. Futures or Tasks that aren’t done when the timeout occurs are simply returned in the second set.return_when indicates when this function should return. It must be one of the following constants:
Constant
Description
- asyncio.FIRST_COMPLETED¶
The function will return when any future finishes or is cancelled.
- asyncio.FIRST_EXCEPTION¶
The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to
ALL_COMPLETED
.- asyncio.ALL_COMPLETED¶
The function will return when all futures finish or are cancelled.
Unlike
wait_for()
,wait()
does not cancel the futures when a timeout occurs.Changed in version 3.10: Removed the loop parameter.
Changed in version 3.11: Passing coroutine objects to
wait()
directly is forbidden.Changed in version 3.12: Added support for generators yielding tasks.
- asyncio.as_completed(aws, *, timeout=None)¶
Run awaitable objects in the aws iterable concurrently. The returned object can be iterated to obtain the results of the awaitables as they finish.
The object returned by
as_completed()
can be iterated as an asynchronous iterator or a plain iterator. When asynchronous iteration is used, the originally-supplied awaitables are yielded if they are tasks or futures. This makes it easy to correlate previously-scheduled tasks with their results. Example:ipv4_connect = create_task(open_connection("127.0.0.1", 80)) ipv6_connect = create_task(open_connection("::1", 80)) tasks = [ipv4_connect, ipv6_connect] async for earliest_connect in as_completed(tasks): # earliest_connect is done. The result can be obtained by # awaiting it or calling earliest_connect.result() reader, writer = await earliest_connect if earliest_connect is ipv6_connect: print("IPv6 connection established.") else: print("IPv4 connection established.")
During asynchronous iteration, implicitly-created tasks will be yielded for supplied awaitables that aren’t tasks or futures.
When used as a plain iterator, each iteration yields a new coroutine that returns the result or raises the exception of the next completed awaitable. This pattern is compatible with Python versions older than 3.13:
ipv4_connect = create_task(open_connection("127.0.0.1", 80)) ipv6_connect = create_task(open_connection("::1", 80)) tasks = [ipv4_connect, ipv6_connect] for next_connect in as_completed(tasks): # next_connect is not one of the original task objects. It must be # awaited to obtain the result value or raise the exception of the # awaitable that finishes next. reader, writer = await next_connect
A
TimeoutError
is raised if the timeout occurs before all awaitables are done. This is raised by theasync for
loop during asynchronous iteration or by the coroutines yielded during plain iteration.Changed in version 3.10: Removed the loop parameter.
Deprecated since version 3.10: Deprecation warning is emitted if not all awaitable objects in the aws iterable are Future-like objects and there is no running event loop.
Changed in version 3.12: Added support for generators yielding tasks.
Changed in version 3.13: The result can now be used as either an asynchronous iterator or as a plain iterator (previously it was only a plain iterator).
Running in Threads¶
- async asyncio.to_thread(func, /, *args, **kwargs)¶
Asynchronously run function func in a separate thread.
Any *args and **kwargs supplied for this function are directly passed to func. Also, the current
contextvars.Context
is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.Return a coroutine that can be awaited to get the eventual result of func.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:
def blocking_io(): print(f"start blocking_io at {time.strftime('%X')}") # Note that time.sleep() can be replaced with any blocking # IO-bound operation, such as file operations. time.sleep(1) print(f"blocking_io complete at {time.strftime('%X')}") async def main(): print(f"started main at {time.strftime('%X')}") await asyncio.gather( asyncio.to_thread(blocking_io), asyncio.sleep(1)) print(f"finished main at {time.strftime('%X')}") asyncio.run(main()) # Expected output: # # started main at 19:50:53 # start blocking_io at 19:50:53 # blocking_io complete at 19:50:54 # finished main at 19:50:54
Directly calling
blocking_io()
in any coroutine would block the event loop for its duration, resulting in an additional 1 second of run time. Instead, by usingasyncio.to_thread()
, we can run it in a separate thread without blocking the event loop.Note
Due to the GIL,
asyncio.to_thread()
can typically only be used to make IO-bound functions non-blocking. However, for extension modules that release the GIL or alternative Python implementations that don’t have one,asyncio.to_thread()
can also be used for CPU-bound functions.Added in version 3.9.
Scheduling From Other Threads¶
- asyncio.run_coroutine_threadsafe(coro, loop)¶
Submit a coroutine to the given event loop. Thread-safe.
Return a
concurrent.futures.Future
to wait for the result from another OS thread.This function is meant to be called from a different OS thread than the one where the event loop is running. Example:
def in_thread(loop: asyncio.AbstractEventLoop) -> None: # Run some blocking IO pathlib.Path("example.txt").write_text("hello world", encoding="utf8") # Create a coroutine coro = asyncio.sleep(1, result=3) # Submit the coroutine to a given loop future = asyncio.run_coroutine_threadsafe(coro, loop) # Wait for the result with an optional timeout argument assert future.result(timeout=2) == 3 async def amain() -> None: # Get the running loop loop = asyncio.get_running_loop() # Run something in a thread await asyncio.to_thread(in_thread, loop)
It’s also possible to run the other way around. Example:
@contextlib.contextmanager def loop_in_thread() -> Generator[asyncio.AbstractEventLoop]: loop_fut = concurrent.futures.Future[asyncio.AbstractEventLoop]() stop_event = asyncio.Event() async def main() -> None: loop_fut.set_result(asyncio.get_running_loop()) await stop_event.wait() with concurrent.futures.ThreadPoolExecutor(1) as tpe: complete_fut = tpe.submit(asyncio.run, main()) for fut in concurrent.futures.as_completed((loop_fut, complete_fut)): if fut is loop_fut: loop = loop_fut.result() try: yield loop finally: loop.call_soon_threadsafe(stop_event.set) else: fut.result() # Create a loop in another thread with loop_in_thread() as loop: # Create a coroutine coro = asyncio.sleep(1, result=3) # Submit the coroutine to a given loop future = asyncio.run_coroutine_threadsafe(coro, loop) # Wait for the result with an optional timeout argument assert future.result(timeout=2) == 3
If an exception is raised in the coroutine, the returned Future will be notified. It can also be used to cancel the task in the event loop:
try: result = future.result(timeout) except TimeoutError: print('The coroutine took too long, cancelling the task...') future.cancel() except Exception as exc: print(f'The coroutine raised an exception: {exc!r}') else: print(f'The coroutine returned: {result!r}')
See the concurrency and multithreading section of the documentation.
Unlike other asyncio functions this function requires the loop argument to be passed explicitly.
Added in version 3.5.1.
Introspection¶
- asyncio.current_task(loop=None)¶
Return the currently running
Task
instance, orNone
if no task is running.If loop is
None
get_running_loop()
is used to get the current loop.Added in version 3.7.
- asyncio.all_tasks(loop=None)¶
Return a set of not yet finished
Task
objects run by the loop.If loop is
None
,get_running_loop()
is used for getting current loop.Added in version 3.7.
- asyncio.iscoroutine(obj)¶
Return
True
if obj is a coroutine object.Added in version 3.4.
Task Object¶
- class asyncio.Task(coro, *, loop=None, name=None, context=None, eager_start=False)¶
A
Future-like
object that runs a Python coroutine. Not thread-safe.Tasks are used to run coroutines in event loops. If a coroutine awaits on a Future, the Task suspends the execution of the coroutine and waits for the completion of the Future. When the Future is done, the execution of the wrapped coroutine resumes.
Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations.
Use the high-level
asyncio.create_task()
function to create Tasks, or the low-levelloop.create_task()
orensure_future()
functions. Manual instantiation of Tasks is discouraged.To cancel a running Task use the
cancel()
method. Calling it will cause the Task to throw aCancelledError
exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.cancelled()
can be used to check if the Task was cancelled. The method returnsTrue
if the wrapped coroutine did not suppress theCancelledError
exception and was actually cancelled.asyncio.Task
inherits fromFuture
all of its APIs exceptFuture.set_result()
andFuture.set_exception()
.An optional keyword-only context argument allows specifying a custom
contextvars.Context
for the coro to run in. If no context is provided, the Task copies the current context and later runs its coroutine in the copied context.An optional keyword-only eager_start argument allows eagerly starting the execution of the
asyncio.Task
at task creation time. If set toTrue
and the event loop is running, the task will start executing the coroutine immediately, until the first time the coroutine blocks. If the coroutine returns or raises without blocking, the task will be finished eagerly and will skip scheduling to the event loop.Changed in version 3.7: Added support for the
contextvars
module.Changed in version 3.8: Added the name parameter.
Deprecated since version 3.10: Deprecation warning is emitted if loop is not specified and there is no running event loop.
Changed in version 3.11: Added the context parameter.
Changed in version 3.12: Added the eager_start parameter.
- done()¶
Return
True
if the Task is done.A Task is done when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.
- result()¶
Return the result of the Task.
If the Task is done, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised.)
If the Task has been cancelled, this method raises a
CancelledError
exception.If the Task’s result isn’t yet available, this method raises an
InvalidStateError
exception.
- exception()¶
Return the exception of the Task.
If the wrapped coroutine raised an exception that exception is returned. If the wrapped coroutine returned normally this method returns
None
.If the Task has been cancelled, this method raises a
CancelledError
exception.If the Task isn’t done yet, this method raises an
InvalidStateError
exception.
- add_done_callback(callback, *, context=None)¶
Add a callback to be run when the Task is done.
This method should only be used in low-level callback-based code.
See the documentation of
Future.add_done_callback()
for more details.
- remove_done_callback(callback)¶
Remove callback from the callbacks list.
This method should only be used in low-level callback-based code.
See the documentation of
Future.remove_done_callback()
for more details.
- get_stack(*, limit=None)¶
Return the list of stack frames for this Task.
If the wrapped coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames.
The frames are always ordered from oldest to newest.
Only one stack frame is returned for a suspended coroutine.
The optional limit argument sets the maximum number of frames to return; by default all available frames are returned. The ordering of the returned list differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.)
- print_stack(*, limit=None, file=None)¶
Print the stack or traceback for this Task.
This produces output similar to that of the traceback module for the frames retrieved by
get_stack()
.The limit argument is passed to
get_stack()
directly.The file argument is an I/O stream to which the output is written; by default output is written to
sys.stdout
.
- get_coro()¶
Return the coroutine object wrapped by the
Task
.Note
This will return
None
for Tasks which have already completed eagerly. See the Eager Task Factory.Added in version 3.8.
Changed in version 3.12: Newly added eager task execution means result may be
None
.
- get_context()¶
Return the
contextvars.Context
object associated with the task.Added in version 3.12.
- get_name()¶
Return the name of the Task.
If no name has been explicitly assigned to the Task, the default asyncio Task implementation generates a default name during instantiation.
Added in version 3.8.
- set_name(value)¶
Set the name of the Task.
The value argument can be any object, which is then converted to a string.
In the default Task implementation, the name will be visible in the
repr()
output of a task object.Added in version 3.8.
- cancel(msg=None)¶
Request the Task to be cancelled.
If the Task is already done or cancelled, return
False
, otherwise, returnTrue
.The method arranges for a
CancelledError
exception to be thrown into the wrapped coroutine on the next cycle of the event loop.The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a
try
… …except CancelledError
…finally
block. Therefore, unlikeFuture.cancel()
,Task.cancel()
does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged. Should the coroutine nevertheless decide to suppress the cancellation, it needs to callTask.uncancel()
in addition to catching the exception.Changed in version 3.9: Added the msg parameter.
Changed in version 3.11: The
msg
parameter is propagated from cancelled task to its awaiter.The following example illustrates how coroutines can intercept the cancellation request:
async def cancel_me(): print('cancel_me(): before sleep') try: # Wait for 1 hour await asyncio.sleep(3600) except asyncio.CancelledError: print('cancel_me(): cancel sleep') raise finally: print('cancel_me(): after sleep') async def main(): # Create a "cancel_me" Task task = asyncio.create_task(cancel_me()) # Wait for 1 second await asyncio.sleep(1) task.cancel() try: await task except asyncio.CancelledError: print("main(): cancel_me is cancelled now") asyncio.run(main()) # Expected output: # # cancel_me(): before sleep # cancel_me(): cancel sleep # cancel_me(): after sleep # main(): cancel_me is cancelled now
- cancelled()¶
Return
True
if the Task is cancelled.The Task is cancelled when the cancellation was requested with
cancel()
and the wrapped coroutine propagated theCancelledError
exception thrown into it.
- uncancel()¶
Decrement the count of cancellation requests to this Task.
Returns the remaining number of cancellation requests.
Note that once execution of a cancelled task completed, further calls to
uncancel()
are ineffective.Added in version 3.11.
This method is used by asyncio’s internals and isn’t expected to be used by end-user code. In particular, if a Task gets successfully uncancelled, this allows for elements of structured concurrency like Task Groups and
asyncio.timeout()
to continue running, isolating cancellation to the respective structured block. For example:async def make_request_with_timeout(): try: async with asyncio.timeout(1): # Structured block affected by the timeout: await make_request() await make_another_request() except TimeoutError: log("There was a timeout") # Outer code not affected by the timeout: await unrelated_code()
While the block with
make_request()
andmake_another_request()
might get cancelled due to the timeout,unrelated_code()
should continue running even in case of the timeout. This is implemented withuncancel()
.TaskGroup
context managers useuncancel()
in a similar fashion.If end-user code is, for some reason, suppressing cancellation by catching
CancelledError
, it needs to call this method to remove the cancellation state.When this method decrements the cancellation count to zero, the method checks if a previous
cancel()
call had arranged forCancelledError
to be thrown into the task. If it hasn’t been thrown yet, that arrangement will be rescinded (by resetting the internal_must_cancel
flag).
Changed in version 3.13: Changed to rescind pending cancellation requests upon reaching zero.
- cancelling()¶
Return the number of pending cancellation requests to this Task, i.e., the number of calls to
cancel()
less the number ofuncancel()
calls.Note that if this number is greater than zero but the Task is still executing,
cancelled()
will still returnFalse
. This is because this number can be lowered by callinguncancel()
, which can lead to the task not being cancelled after all if the cancellation requests go down to zero.This method is used by asyncio’s internals and isn’t expected to be used by end-user code. See
uncancel()
for more details.Added in version 3.11.


Generator Objects

Generator Objects¶
Generator objects are what Python uses to implement generator iterators. They
are normally created by iterating over a function that yields values, rather
than explicitly calling PyGen_New()
or PyGen_NewWithQualName()
.
-
type PyGenObject¶
The C structure used for generator objects.
-
PyTypeObject PyGen_Type¶
The type object corresponding to generator objects.
-
int PyGen_Check(PyObject *ob)¶
Return true if ob is a generator object; ob must not be
NULL
. This function always succeeds.
-
int PyGen_CheckExact(PyObject *ob)¶
Return true if ob’s type is
PyGen_Type
; ob must not beNULL
. This function always succeeds.
-
PyObject *PyGen_New(PyFrameObject *frame)¶
- Return value: New reference.
Create and return a new generator object based on the frame object. A reference to frame is stolen by this function. The argument must not be
NULL
.
-
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)¶
- Return value: New reference.
Create and return a new generator object based on the frame object, with
__name__
and__qualname__
set to name and qualname. A reference to frame is stolen by this function. The frame argument must not beNULL
.
-
PyCodeObject *PyGen_GetCode(PyGenObject *gen)¶
Return a new strong reference to the code object wrapped by gen. This function always succeeds.
Asynchronous Generator Objects¶
See also
-
PyTypeObject PyAsyncGen_Type¶
The type object corresponding to asynchronous generator objects. This is available as
types.AsyncGeneratorType
in the Python layer.Added in version 3.6.
-
PyObject *PyAsyncGen_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)¶
Create a new asynchronous generator wrapping frame, with
__name__
and__qualname__
set to name and qualname. frame is stolen by this function and must not beNULL
.On success, this function returns a strong reference to the new asynchronous generator. On failure, this function returns
NULL
with an exception set.Added in version 3.6.
Deprecated API¶
-
PyAsyncGenASend_CheckExact(op)¶
This is a soft deprecated API that was included in Python’s C API by mistake.
It is solely here for completeness; do not use this API.


— The shadow password database

spwd
— The shadow password database¶
Deprecated since version 3.11, removed in version 3.13.
This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.
A possible replacement is the third-party library python-pam. This library is not supported or maintained by the Python core team.
The last version of Python that provided the spwd
module was
Python 3.12.


What’s New In Python 3.1

What’s New In Python 3.1¶
- Author:
Raymond Hettinger
This article explains the new features in Python 3.1, compared to 3.0. Python 3.1 was released on June 27, 2009.
PEP 372: Ordered Dictionaries¶
Regular Python dictionaries iterate over key/value pairs in arbitrary order.
Over the years, a number of authors have written alternative implementations
that remember the order that the keys were originally inserted. Based on
the experiences from those implementations, a new
collections.OrderedDict
class has been introduced.
The OrderedDict API is substantially the same as regular dictionaries but will iterate over keys and values in a guaranteed order depending on when a key was first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
The standard library now supports use of ordered dictionaries in several
modules. The configparser
module uses them by default. This lets
configuration files be read, modified, and then written back in their original
order. The _asdict() method for collections.namedtuple()
now
returns an ordered dictionary with the values appearing in the same order as
the underlying tuple indices. The json
module is being built-out with
an object_pairs_hook to allow OrderedDicts to be built by the decoder.
Support was also added for third-party tools like PyYAML.
See also
- PEP 372 - Ordered Dictionaries
PEP written by Armin Ronacher and Raymond Hettinger. Implementation written by Raymond Hettinger.
Since an ordered dictionary remembers its insertion order, it can be used in conjunction with sorting to make a sorted dictionary:
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.
PEP 378: Format Specifier for Thousands Separator¶
The built-in format()
function and the str.format()
method use
a mini-language that now includes a simple, non-locale aware way to format
a number with a thousands separator. That provides a way to humanize a
program’s output, improving its professional appearance and readability:
>>> format(1234567, ',d')
'1,234,567'
>>> format(1234567.89, ',.2f')
'1,234,567.89'
>>> format(12345.6 + 8901234.12j, ',f')
'12,345.600000+8,901,234.120000j'
>>> format(Decimal('1234567.89'), ',f')
'1,234,567.89'
The supported types are int
, float
, complex
and decimal.Decimal
.
Discussions are underway about how to specify alternative separators like dots, spaces, apostrophes, or underscores. Locale-aware applications should use the existing n format specifier which already has some support for thousands separators.
See also
- PEP 378 - Format Specifier for Thousands Separator
PEP written by Raymond Hettinger and implemented by Eric Smith and Mark Dickinson.
Other Language Changes¶
Some smaller changes made to the core Python language are:
Directories and zip archives containing a
__main__.py
file can now be executed directly by passing their name to the interpreter. The directory/zipfile is automatically inserted as the first entry in sys.path. (Suggestion and initial patch by Andy Chu; revised patch by Phillip J. Eby and Nick Coghlan; bpo-1739468.)The
int()
type gained abit_length
method that returns the number of bits necessary to represent its argument in binary:>>> n = 37 >>> bin(37) '0b100101' >>> n.bit_length() 6 >>> n = 2**123-1 >>> n.bit_length() 123 >>> (n+1).bit_length() 124
(Contributed by Fredrik Johansson, Victor Stinner, Raymond Hettinger, and Mark Dickinson; bpo-3439.)
The fields in
format()
strings can now be automatically numbered:>>> 'Sir {} of {}'.format('Gallahad', 'Camelot') 'Sir Gallahad of Camelot'
Formerly, the string would have required numbered fields such as:
'Sir {0} of {1}'
.(Contributed by Eric Smith; bpo-5237.)
The
string.maketrans()
function is deprecated and is replaced by new static methods,bytes.maketrans()
andbytearray.maketrans()
. This change solves the confusion around which types were supported by thestring
module. Now,str
,bytes
, andbytearray
each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.(Contributed by Georg Brandl; bpo-5675.)
The syntax of the
with
statement now allows multiple context managers in a single statement:>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile: ... for line in infile: ... if '<critical>' in line: ... outfile.write(line)
With the new syntax, the
contextlib.nested()
function is no longer needed and is now deprecated.(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094.)
round(x, n)
now returns an integer if x is an integer. Previously it returned a float:>>> round(1123, -2) 1100
(Contributed by Mark Dickinson; bpo-4707.)
Python now uses David Gay’s algorithm for finding the shortest floating-point representation that doesn’t change its value. This should help mitigate some of the confusion surrounding binary floating-point numbers.
The significance is easily seen with a number like
1.1
which does not have an exact equivalent in binary floating point. Since there is no exact equivalent, an expression likefloat('1.1')
evaluates to the nearest representable value which is0x1.199999999999ap+0
in hex or1.100000000000000088817841970012523233890533447265625
in decimal. That nearest value was and still is used in subsequent floating-point calculations.What is new is how the number gets displayed. Formerly, Python used a simple approach. The value of
repr(1.1)
was computed asformat(1.1, '.17g')
which evaluated to'1.1000000000000001'
. The advantage of using 17 digits was that it relied on IEEE-754 guarantees to assure thateval(repr(1.1))
would round-trip exactly to its original value. The disadvantage is that many people found the output to be confusing (mistaking intrinsic limitations of binary floating-point representation as being a problem with Python itself).The new algorithm for
repr(1.1)
is smarter and returns'1.1'
. Effectively, it searches all equivalent string representations (ones that get stored with the same underlying float value) and returns the shortest representation.The new algorithm tends to emit cleaner representations when possible, but it does not change the underlying values. So, it is still the case that
1.1 + 2.2 != 3.3
even though the representations may suggest otherwise.The new algorithm depends on certain features in the underlying floating-point implementation. If the required features are not found, the old algorithm will continue to be used. Also, the text pickle protocols assure cross-platform portability by using the old algorithm.
(Contributed by Eric Smith and Mark Dickinson; bpo-1580)
New, Improved, and Deprecated Modules¶
Added a
collections.Counter
class to support convenient counting of unique items in a sequence or iterable:>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) Counter({'blue': 3, 'red': 2, 'green': 1})
(Contributed by Raymond Hettinger; bpo-1696199.)
Added a new module,
tkinter.ttk
for access to the Tk themed widget set. The basic idea of ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.(Contributed by Guilherme Polo; bpo-2983.)
The
gzip.GzipFile
andbz2.BZ2File
classes now support the context management protocol:>>> # Automatically close file after writing >>> with gzip.GzipFile(filename, "wb") as f: ... f.write(b"xxx")
(Contributed by Antoine Pitrou.)
The
decimal
module now supports methods for creating a decimal object from a binaryfloat
. The conversion is exact but can sometimes be surprising:>>> Decimal.from_float(1.1) Decimal('1.100000000000000088817841970012523233890533447265625')
The long decimal result shows the actual binary fraction being stored for 1.1. The fraction has many digits because 1.1 cannot be exactly represented in binary.
(Contributed by Raymond Hettinger and Mark Dickinson.)
The
itertools
module grew two new functions. Theitertools.combinations_with_replacement()
function is one of four for generating combinatorics including permutations and Cartesian products. Theitertools.compress()
function mimics its namesake from APL. Also, the existingitertools.count()
function now has an optional step argument and can accept any type of counting sequence includingfractions.Fraction
anddecimal.Decimal
:>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)] ['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE'] >>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0])) [2, 3, 5, 7] >>> c = count(start=Fraction(1,2), step=Fraction(1,6)) >>> [next(c), next(c), next(c), next(c)] [Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]
(Contributed by Raymond Hettinger.)
collections.namedtuple()
now supports a keyword argument rename which lets invalid fieldnames be automatically converted to positional names in the form _0, _1, etc. This is useful when the field names are being created by an external source such as a CSV header, SQL field list, or user input:>>> query = input() SELECT region, dept, count(*) FROM main GROUPBY region, dept >>> cursor.execute(query) >>> query_fields = [desc[0] for desc in cursor.description] >>> UserQuery = namedtuple('UserQuery', query_fields, rename=True) >>> pprint.pprint([UserQuery(*row) for row in cursor]) [UserQuery(region='South', dept='Shipping', _2=185), UserQuery(region='North', dept='Accounting', _2=37), UserQuery(region='West', dept='Sales', _2=419)]
(Contributed by Raymond Hettinger; bpo-1818.)
The
re.sub()
,re.subn()
andre.split()
functions now accept a flags parameter.(Contributed by Gregory Smith.)
The
logging
module now implements a simplelogging.NullHandler
class for applications that are not using logging but are calling library code that does. Setting-up a null handler will suppress spurious warnings such as “No handlers could be found for logger foo”:>>> h = logging.NullHandler() >>> logging.getLogger("foo").addHandler(h)
(Contributed by Vinay Sajip; bpo-4384).
The
runpy
module which supports the-m
command line switch now supports the execution of packages by looking for and executing a__main__
submodule when a package name is supplied.(Contributed by Andi Vajda; bpo-4195.)
The
pdb
module can now access and display source code loaded viazipimport
(or any other conformant PEP 302 loader).(Contributed by Alexander Belopolsky; bpo-4201.)
functools.partial
objects can now be pickled.
(Suggested by Antoine Pitrou and Jesse Noller. Implemented by Jack Diederich; bpo-5228.)
Add
pydoc
help topics for symbols so thathelp('@')
works as expected in the interactive environment.(Contributed by David Laban; bpo-4739.)
The
unittest
module now supports skipping individual tests or classes of tests. And it supports marking a test as an expected failure, a test that is known to be broken, but shouldn’t be counted as a failure on a TestResult:class TestGizmo(unittest.TestCase): @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_gizmo_on_windows(self): ... @unittest.expectedFailure def test_gimzo_without_required_library(self): ...
Also, tests for exceptions have been builtout to work with context managers using the
with
statement:def test_division_by_zero(self): with self.assertRaises(ZeroDivisionError): x / 0
In addition, several new assertion methods were added including
assertSetEqual()
,assertDictEqual()
,assertDictContainsSubset()
,assertListEqual()
,assertTupleEqual()
,assertSequenceEqual()
,assertRaisesRegexp()
,assertIsNone()
, andassertIsNotNone()
.(Contributed by Benjamin Peterson and Antoine Pitrou.)
The
io
module has three new constants for theseek()
method:SEEK_SET
,SEEK_CUR
, andSEEK_END
.The
sys.version_info
tuple is now a named tuple:>>> sys.version_info sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)
(Contributed by Ross Light; bpo-4285.)
The
nntplib
andimaplib
modules now support IPv6.The
pickle
module has been adapted for better interoperability with Python 2.x when used with protocol 2 or lower. The reorganization of the standard library changed the formal reference for many objects. For example,__builtin__.set
in Python 2 is calledbuiltins.set
in Python 3. This change confounded efforts to share data between different versions of Python. But now when protocol 2 or lower is selected, the pickler will automatically use the old Python 2 names for both loading and dumping. This remapping is turned-on by default but can be disabled with the fix_imports option:>>> s = {1, 2, 3} >>> pickle.dumps(s, protocol=0) b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.' >>> pickle.dumps(s, protocol=0, fix_imports=False) b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
An unfortunate but unavoidable side-effect of this change is that protocol 2 pickles produced by Python 3.1 won’t be readable with Python 3.0. The latest pickle protocol, protocol 3, should be used when migrating data between Python 3.x implementations, as it doesn’t attempt to remain compatible with Python 2.x.
(Contributed by Alexandre Vassalotti and Antoine Pitrou, bpo-6137.)
A new module,
importlib
was added. It provides a complete, portable, pure Python reference implementation of theimport
statement and its counterpart, the__import__()
function. It represents a substantial step forward in documenting and defining the actions that take place during imports.(Contributed by Brett Cannon.)
Optimizations¶
Major performance enhancements have been added:
The new I/O library (as defined in PEP 3116) was mostly written in Python and quickly proved to be a problematic bottleneck in Python 3.0. In Python 3.1, the I/O library has been entirely rewritten in C and is 2 to 20 times faster depending on the task at hand. The pure Python version is still available for experimentation purposes through the
_pyio
module.(Contributed by Amaury Forgeot d’Arc and Antoine Pitrou.)
Added a heuristic so that tuples and dicts containing only untrackable objects are not tracked by the garbage collector. This can reduce the size of collections and therefore the garbage collection overhead on long-running programs, depending on their particular use of datatypes.
(Contributed by Antoine Pitrou, bpo-4688.)
Enabling a configure option named
--with-computed-gotos
on compilers that support it (notably: gcc, SunPro, icc), the bytecode evaluation loop is compiled with a new dispatch mechanism which gives speedups of up to 20%, depending on the system, the compiler, and the benchmark.(Contributed by Antoine Pitrou along with a number of other participants, bpo-4753).
The decoding of UTF-8, UTF-16 and LATIN-1 is now two to four times faster.
(Contributed by Antoine Pitrou and Amaury Forgeot d’Arc, bpo-4868.)
The
json
module now has a C extension to substantially improve its performance. In addition, the API was modified so that json works only withstr
, not withbytes
. That change makes the module closely match the JSON specification which is defined in terms of Unicode.(Contributed by Bob Ippolito and converted to Py3.1 by Antoine Pitrou and Benjamin Peterson; bpo-4136.)
Unpickling now interns the attribute names of pickled objects. This saves memory and allows pickles to be smaller.
(Contributed by Jake McGuire and Antoine Pitrou; bpo-5084.)
IDLE¶
IDLE’s format menu now provides an option to strip trailing whitespace from a source file.
(Contributed by Roger D. Serwy; bpo-5150.)
Build and C API Changes¶
Changes to Python’s build process and to the C API include:
Integers are now stored internally either in base
2**15
or in base2**30
, the base being determined at build time. Previously, they were always stored in base2**15
. Using base2**30
gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base2**30
on 64-bit machines and base2**15
on 32-bit machines; on Unix, there’s a new configure option--enable-big-digits
that can be used to override this default.Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there’s a new
sys.int_info
that provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:>>> import sys >>> sys.int_info sys.int_info(bits_per_digit=30, sizeof_digit=4)
(Contributed by Mark Dickinson; bpo-4258.)
The
PyLong_AsUnsignedLongLong()
function now handles a negative pylong by raisingOverflowError
instead ofTypeError
.(Contributed by Mark Dickinson and Lisandro Dalcrin; bpo-5175.)
Deprecated
PyNumber_Int()
. UsePyNumber_Long()
instead.(Contributed by Mark Dickinson; bpo-4910.)
Added a new
PyOS_string_to_double()
function to replace the deprecated functionsPyOS_ascii_strtod()
andPyOS_ascii_atof()
.(Contributed by Mark Dickinson; bpo-5914.)
Added
PyCapsule
as a replacement for thePyCObject
API. The principal difference is that the new type has a well defined interface for passing typing safety information and a less complicated signature for calling a destructor. The old type had a problematic API and is now deprecated.(Contributed by Larry Hastings; bpo-5630.)
Porting to Python 3.1¶
This section lists previously described changes and other bugfixes that may require changes to your code:
The new floating-point string representations can break existing doctests. For example:
def e(): '''Compute the base of natural logarithms. >>> e() 2.7182818284590451 ''' return sum(1/math.factorial(x) for x in reversed(range(30))) doctest.testmod() ********************************************************************** Failed example: e() Expected: 2.7182818284590451 Got: 2.718281828459045 **********************************************************************
The automatic name remapping in the pickle module for protocol 2 or lower can make Python 3.1 pickles unreadable in Python 3.0. One solution is to use protocol 3. Another solution is to set the fix_imports option to
False
. See the discussion above for more details.


Abstract Objects Layer

Abstract Objects Layer¶
The functions in this chapter interact with Python objects regardless of their type, or with wide classes of object types (e.g. all numerical types, or all sequence types). When used on object types for which they do not apply, they will raise a Python exception.
It is not possible to use these functions on objects that are not properly
initialized, such as a list object that has been created by PyList_New()
,
but whose items have not been set to some non-NULL
value yet.