Changelog

Python seguinte

Data de lançamento: XXXX-XX-XX

Segurança

  • gh-161192: Update bundled libexpat to version 2.10.0 for the fixes to CVE 2026-113351, CVE 2026-115506, CVE 2026-117610 and CVE 2026-118370.

  • CVE 2026-116566, gh-160898: socket.getaddrinfo() now rejects null bytes within host and port parameters as this previously caused the values to be silently truncated.

  • gh-160279: Prevent venv from importing modules from the root of an existing virtual environment when installing or upgrading pip.

  • gh-160499: Fix unbounded memory growth in asyncio TLS connections when a peer stops reading but keeps sending records that make OpenSSL generate its own replies (such as TLS 1.2 renegotiation alerts). Reading from the peer is now paused when this output accumulates, instead of only when application data does.

  • gh-160506: Fix os.path.realpath() on Windows returning the wrong path for a broken relative symbolic link reached through a symbolic link to a directory. This allowed tarfile extraction with the 'data' or 'tar' filter to create a file outside the destination directory.

  • gh-161323: On Windows, the 'tar' and 'data' tarfile extraction filters now refuse member names and link targets that have a drive but are not absolute, such as C:foo, with AbsolutePathError or AbsoluteLinkError. Such members could be extracted outside the destination directory. Fixes CVE 2026-107784.

  • gh-160420: Fix zoneinfo.ZoneInfo on Windows accepting keys in which a component after a / starts with a drive letter, such as America/C:\file. Such a key could open a file outside the tzdata package; it now raises ValueError.

  • gh-160300: Correge http.cookiejar.DefaultCookiePolicy que aceitava e retornava cookies com um atributo Version negativo, sem verificar se o domínio correspondia ao host da requisição. Tais cookies agora são ignorados.

  • CVE 2026-114583, gh-160097: tarfile.tar_filter() agora rejeita membros do tipo link cujo caminho resulte no próprio diretório de destino, assim como tarfile.data_filter() já fazia.

  • CVE 2026-115557, gh-160040: O módulo ssl agora rejeita cadeias de certificados TLS que contenham qualquer uma das chaves de autoridades certificadoras (CA) intermediárias da eMudhra que foram comprometidas. Esta é uma medida extraordinária e uma última linha de defesa: a remoção da confiança é, primordialmente, uma responsabilidade do repositório de certificados raiz da plataforma; a lista de bloqueio (denylist) embutida serve apenas para impedir conexões enquanto a atualização correspondente ainda não tiver chegado ao sistema operacional, a uma imagem de contêiner ou a um repositório de certificados incluído em diversos pacotes Python. Entradas são adicionadas a essa lista de bloqueio apenas sob critérios extremamente rigorosos. A verificação na lista de bloqueio baseia-se na chave pública (o hash SHA-256 do campo SubjectPublicKeyInfo, conforme a RFC 5280), abrangendo, portanto, também certificados com assinatura cruzada (cross-signed) que reutilizam uma das chaves consideradas não confiáveis.

  • gh-159894: Bump the version of pip bundled in ensurepip to version 26.2.2.

  • gh-159428: mimetypes no longer reads the files listed in mimetypes.knownfiles by default on Windows, and uses only the registry.

  • gh-158928: Fix a buffer overflow when initializing a bytearray from an iterator.

  • gh-157953: Update bundled libexpat to version 2.9.0.

Núcleo e embutidos

  • gh-161419: Fix a crash in the free-threaded build where a weak reference could revive an object whose finalizer had already run during deallocation, causing it to be deallocated twice.

  • gh-161288: Fix a crash in the perf trampoline (-X perf) on builds with clang’s -fsanitize=function, which -fsanitize=undefined enables since clang 17.

  • gh-159184: Fix a leak of NaN constants in code objects created by marshal.loads() on the free-threaded build.

  • gh-161229: __lazy_import__() now treats None for globals and locals the same as omitting them, matching its signature.

  • gh-160773: Fix a crash in str() of an OSError when formatting one of its attributes modifies the others.

  • gh-160682: Fix a bug in the free-threaded build where garbage collection could prematurely collect the function object of a running method.

  • gh-153568: Speed up ast.parse() by ~15.8% and reduce the memory used by ~51.6% by storing node attributes as inline values instead of in a per-node dictionary.

  • gh-160491: Corrige a localização informada para sequências de escape inválidas em f-strings e t-strings. O SyntaxError agora aponta para a parte literal que contém o escape, em vez de apontar para as aspas de fechamento.

  • Corrige uma falha no módulo tokenize que ocorria quando um colchete de fechamento aparecia sem o correspondente de abertura logo após a chave de abertura de um campo de substituição em uma f-string ou t-string – por exemplo, em f'{]a'. Agora, o módulo emite o mesmo erro de falta de correspondência (unmatched) que o analisador sintático.

  • gh-160245: Reduce the size of parser memo entries on 64-bit platforms by reordering fields to remove padding. Patch by Shamil Abdulaev.

  • gh-106045: Correção na descoberta de caminhos pelo módulo venv para casos em que o executável base aponta para um local fora da instalação indicada pela chave home no arquivo pyvenv.cfg. A biblioteca padrão passa a ser localizada a partir de home, e os módulos de extensão, a partir da instalação do executável resolvido, em vez de recorrer ao prefixo definido durante a compilação.

  • gh-160162: Corrige uma falha em plataformas de 32 bits que ocorria ao realizar um deslocamento à esquerda (left shift) em um int por uma quantidade próxima a sys.maxsize * sys.int_info.bits_per_digit. Agora, uma OverflowError é levantada, assim como ocorre para outras quantidades excessivamente grandes.

  • gh-160179: Fix bytearray.__init__() leaving uninitialized memory in the object when it fails on a list or tuple containing an integer not in range(256). The object is now empty after the failed call.

  • gh-160132: Reduce memory usage during compilation by reordering the fields of the internal basic block structure to reduce padding. Patch by Shamil Abdulaev.

  • gh-159739: Raise MemoryError instead of returning an incorrect result if round() runs out of memory while rounding a float.

  • gh-159739: Fix a possible crash when assigning metadata to classmethod or staticmethod objects.

  • gh-159739: Fix a race in list.__sizeof__() when a list is concurrently resized on a free-threaded build.

  • gh-159739: Fix a reference leak when the value of a type alias is evaluated recursively or concurrently.

  • gh-159739: Fix a crash in free-threaded builds when codecs.unregister() is called concurrently.

  • gh-160368: On Linux, allow timed semaphore waits to use the monotonic clock when sem_clockwait is available at runtime, even if Python was built with older libc headers.

  • gh-159493: Superinstructions are now formed after the compiler decides which LOAD_FAST instructions can borrow their reference. This fixes reference count contention slowdown on the free-threaded build for single-line loops and comprehensions.

  • gh-159963: Fix a regression in Python 3.15.0 where threads importing submodules of packages for the first time could raise _DeadlockError or a spurious “partially initialized module” ImportError, or block one another, with no circular import involved. importlib.import_module() now returns the partially initialized module in a cross-thread circular import, as the import statement does, instead of raising _DeadlockError.

  • gh-158195: Fix a deadlock in the free-threaded build between a thread that stops the world while running Python code under the type lock (for example a custom metaclass mro() or the __eq__ of a str subclass used as a class __dict__ key) and a thread that assigns to a special method or to __bases__ of a class. The type lock is no longer held while waiting for a stop-the-world; the prepared slot, MRO and bases updates are validated with the world stopped and recomputed if they went stale.

  • gh-159739: Fix reference leaks when free-threaded garbage collection aborts early because of an allocation error.

  • gh-159739: Prevent free-threaded builds from interning and immortalizing complex subclasses in code object constants.

  • gh-159739: Fix a reference leak in binary, ternary, and comparison operations on weak reference proxies when another operand is a dead proxy.

  • gh-159739: Fix a crash when constructing an error for invalid generic alias arguments.

  • gh-159739: Allow the garbage collector to break reference cycles involving property accessors or names.

  • gh-159860: Fix false sharing between the per-thread QSBR states in the free-threaded build on AArch64 CPUs with 128-byte cache lines, such as Apple Silicon. CPU-bound threads that share no objects now scale like processes there.

  • gh-159739: Avoid a crash if allocation fails while creating a string.templatelib.Template iterator.

  • gh-159739: Propagate errors during generic class construction and avoid a crash after failed generic alias substitution.

  • gh-159739: Raise OverflowError when the absolute value of a dynamic printf-style formatting width is too large.

  • gh-159739: Fix a reference leak in gc.get_objects() and gc.get_referrers() when an internal allocation fails in the free-threaded build.

  • gh-159739: Fix a crash in warnings.warn() when skip_file_prefixes is an empty tuple subclass. Propagate allocation errors when creating the fallback filename.

  • gh-159739: Fix memory leaks during interpreter startup when a path configuration file is empty or too large, or when an audit hook rejects a command.

  • gh-159739: Avoid a crash when an interpreter configuration string cannot be encoded as UTF-8.

  • gh-159739: Preserve the original SyntaxError if allocating optional error metadata fails.

  • gh-159739: Avoid a crash if formatting an integer with the c presentation type runs out of memory.

  • gh-159739: Avoid a crash when a module filename cannot be encoded as UTF-8.

  • gh-159813: Add a fast path for None in PyUnicodeWriter_WriteRepr(). Patch by Donghee Na.

  • gh-159652: Fix a hang when an import fails with RecursionError because the C stack is nearly exhausted: releasing the import locks could itself fail and leave the global import lock or a module lock held forever, so that later imports in other threads blocked indefinitely. The import system now raises RecursionError before taking an import lock when there is not enough stack left to release it.

  • gh-159603: On FreeBSD, call pthread_attr_get_np() to get the stack size (and guard size) of the current thread. Patch by Victor Stinner.

  • gh-159564: Improve the performance and thread scaling of dereferencing weak references in the free-threaded build. Dereferencing a weak reference no longer takes a lock.

  • gh-87613: Speed up calling slice by adding a vectorcall implementation of the constructor generated by Argument Clinic. Patch by Pieter Eendebak.

  • gh-130279: Fix bug where compiler did not set the right exception handler for some jump instructions.

  • gh-87613: Speed up creating weakref.ref objects by adding a vectorcall implementation of the constructor generated by Argument Clinic. Patch by Pieter Eendebak.

  • gh-159449: Fix a free-threaded asyncio race leading to segfaults.

  • gh-132042: Speed up class creation by resolving the special method slots of a new class with one pass over each class dict along the MRO instead of one lookup per slot name and per class.

  • gh-159434: Fix reading a function’s __annotations__ using borrowed references to __annotate__ and the internal annotations tuple while running code that can replace them. If __annotations__ is set while __annotate__ runs, the newly set value is now kept.

  • gh-159431: Fix an assertion failure, or an immortal object becoming mortal, on the free threaded build when an object passed to the internal delayed decref mechanism is immortal or becomes immortal before the delayed decref is processed by the garbage collector.

  • gh-159430: Report the correct exception if looking up __bytes__() raises an exception while performing %-formatting of bytes.

  • gh-159399: Fix a crash in codecs.encode() and codecs.decode() in the free-threaded build when another thread concurrently unregisters a codec search function. Patch by Christian Aurich Zanettini Martins.

  • gh-159320: Add dynamic detection of stack sizes on Android, allowing safer deep recursion.

  • gh-159294: Fix a crash in a debug build when creating an ExceptionGroup or BaseExceptionGroup fails with MemoryError. Patch by Christian Aurich Zanettini Martins.

  • gh-159288: Fix a crash when walking a very long chain of lazy import placeholders, as created by an aliased dotted import such as lazy import a.b.c as d. RecursionError is now raised instead.

  • gh-159136: Setting __name__, __qualname__, __doc__ or __module__ on a function no longer stops all threads in the free-threaded build. The setters now use the per-object lock and defer freeing the old value with QSBR, the same approach used for generator __name__. This fixes a large slowdown in multi-threaded code using functools.wraps() since 3.14.7. Readers of these attributes now use atomic loads, and argument error reporting reads __qualname__ after keyword comparisons, which may execute Python code and replace it. Previously this could use a freed object.

  • gh-159244: Fix a crash in dict and dict.update() in the free-threaded build when another thread concurrently mutates a list used as a key/value pair. Patch by Christian Aurich Zanettini Martins.

  • gh-68241: Add EXIT_FAILURE and EXIT_SUCCESS in the sys module.

  • gh-159188: In the free-threaded build, compile() no longer immortalizes the constants of the code objects when it is given an AST object, as was already the case for a source string. The output of marshal for such code no longer depends on the code objects which were created before in the process.

  • gh-159111: Update mimalloc version from 2.1.2 to 2.5.2. Patch by Donghee Na.

  • gh-159041: Fix a use-after-free in asyncio task bookkeeping when a finalizer creates a task during thread shutdown.

  • gh-158973: Reset the warnings lock in the child after os.fork(), before clearing other threads’ states, to avoid deadlocks when their finalizers issue warnings. Preserve the lock’s recursion depth if the forking thread owns it.

  • gh-87613: Speed up bytes and bytearray construction by adding O protocolo vectorcall support.

  • gh-158816: Speed up deleting items from split dictionaries (for example the materialized __dict__ of an instance with inline values) by skipping a redundant hash table probe.

  • gh-158197: Fix crashes and debug-build assertion failures in the free-threaded build when iterating over a split dictionary while another thread deletes entries or clears it. Publish insertion-order updates atomically so readers cannot observe an increased size before the corresponding order entry is initialized.

  • gh-158121: Fix missing sys.monitoring INSTRUCTION events when a LINE callback returns sys.monitoring.DISABLE.

  • gh-158304: Speed up iteration over asynchronous generators: values yielded to async for no longer create and discard a StopIteration exception at every nesting level. The async_generators pyperformance benchmark is about 30% faster. Patch by Shamil Abdulaev.

  • gh-157746: Reduce the overhead of PyErr_CheckSignals() when no signal is pending: the cheap flag checks are now done before the main-thread check and the remote debugger configuration lookup.

  • gh-132414: Quote the invalid option in the error message for an unknown command-line option: Invalid option '-z' instead of Unknown option: -z. A stray space, as passed by a shebang line like #!/usr/bin/python3 -q -i, is now reported as Invalid option '- '.

  • gh-157361: Implement aiter() in Python instead of C, in the frozen _pybuiltins module. The async iterator returned by aiter(callable, ...) now has a plain coroutine __anext__(), so introspection tools such as asyncio.print_call_graph() can see through it into the awaited callable result.

  • gh-157194: Fix a data race in the free-threaded build, reported by ThreadSanitizer, between the specializer reading an instruction opcode and another thread writing it. Only reachable when thread-local bytecode is disabled with -X tlbc=0, which makes threads share one copy of the bytecode.

  • gh-156443: Speed up float() conversion and true division of large int values.

  • gh-135385: Reduce the memory consumption of instances of classes which define __slots__ and also have a __dict__. Space for the attributes stored in slots is no longer reserved in the inline values of every instance.

  • gh-106045: Fix standard library discovery in virtual environments created from a Python executable symlink located outside its base installation.

  • gh-156399: Fix a regression where attribute access on a types.ModuleType subclass could bypass a data descriptor defined on the subclass. The LOAD_ATTR_MODULE specialization guarded on tp_getattro, which subclasses inherit, and then read the module dictionary directly.

  • gh-127716: On the free-threaded build, memoryview lifetime and bookkeeping operations are now thread safe: an operation that reads the buffer holds the managed buffer for its duration, so a concurrent release() can no longer free the buffer under it; slicing a memoryview from several threads no longer loses buffer registrations and raises ValueError: operation forbidden on released memoryview object; and hash() of a memoryview is no longer a data race. As a result release() may now return while an operation started by another thread is still running, see Segurança para thread para objetos memoryview.

  • gh-154318: Fix a crash when hashing a deeply nested tuple or frozendict. A RecursionError is now raised instead of overflowing the C stack.

  • gh-153568: Speed up parsing of simple expressions by recognizing single-token atoms without descending the full precedence rule chain.

  • gh-153014: Fix a data race on the garbage collector debug flag in free-threading builds: gc.set_debug() and gc.get_debug() now access it atomically.

  • gh-152631: Fix ast.parse() ability to parse lazy imports with feature_version older than 3.15, now it properly raises SyntaxError.

  • gh-149816: Fix a race in free-threaded builds where storing an instance attribute could use a stale borrowed reference to an instance __dict__ after another thread replaced it.

  • gh-151818: Fix a double-free crash in list.append() (the specialized CALL_LIST_APPEND instruction) when growing the list fails with MemoryError.

  • gh-151060: Fix a crash or memory corruption in sum() when summing a float subclass instance into a complex running total.

  • gh-150075: tar.addfile() now sets member offsets in TarInfo objects

  • gh-69605: Fix REPL completions inserted incorrectly when there was spaces in import statements.

  • gh-69605: Insert import after from x.y.z <tab> in the REPL auto-completion.

  • gh-145019: Improve SyntaxError when match alternative patterns bind different names. Patch by Bénédikt Tran.

  • gh-137966: Add support for additional special names to the built-in help() function. Patch by Adam Hartz.

  • gh-125873: Improved error message when an environment variable is misconfigured.

  • gh-116477: Speed up the range object constructor in the case of a single argument.

Biblioteca

Documentação

  • gh-138277: Rearranged documentation search results to emphasize built-in types and functions. Patch by Adam Hartz.

  • gh-107689: Added docstrings to abstract ctypes.

Testes

  • gh-161517: Fix test_gdb when Python is built out-of-tree and Python is run from a virtual environment. Previously, test_gdb was just skipped. Patch by Victor Stinner.

  • gh-161263: Skip tests which use MD5 algorithm for WWW-Authenticate challenges when libssl is in FIPS mode.

  • gh-158646: Fix a race in test_asyncio.test_sslproto where the server side of test_shutdown_corrupted_ssl_sends_close_notify could fail with a connection reset on Windows.

  • gh-107862: Add hypothesis.stateful and the timezones() and ip_addresses() strategies to the Hypothesis stubs used when Hypothesis is not installed.

  • gh-159293: Restore the recursion limit after the free-threading recursion-limit race test to avoid failures in subsequent tests run in the same process.

  • gh-158975: Replace fixed sleeps used for synchronization in multiprocessing tests with bounded waits to avoid failures on slow or overloaded systems. Ensure pool cleanup runs even when assertions fail in the imap buffer tests.

  • gh-158895: When run in GitHub Actions, test.regrtest now annotates each test failure in the job log and writes a summary of the failures to the job summary.

Construção

  • gh-75929: Fix a configure probe that could omit functions such as os.fchdir() from builds using -Wall -Werror.

  • gh-160704: Fix C11-C17 builds with old C library headers that do not define static_assert, including glibc versions older than 2.16.

  • gh-160689: The build helper programs Programs/_freeze_module and _bootstrap_python are now linked only with the modules of Modules/Setup.bootstrap, instead of with every static module. Builtin modules added via Modules/Setup.local or MODULE_BUILDTYPE=static can now depend on frozen modules or on getpath.

  • gh-128884: Report a configuration error when --enable-bolt is used with build flags that explicitly request the Cortex-A53 erratum 843419 workaround. Document how to disable the workaround for builds that will not run on affected processors.

  • gh-128883: Fix crashes with -X perf and -X perf_jit in BOLT builds. The ELF perf trampoline templates now use read-only data sections.

  • gh-128884: Fix --enable-bolt build failures on AArch64 with recent LLVM: pass -frame-opt=hot only on x86. Patch by Donghee Na.

  • gh-160004: Fix the paths in the PEP 739 build-details.json file generated by Tools/build/generate-build-details.py with both --relative-paths and --config-file-path. Previously, every path except base_prefix was wrong and depended on the directory the script was run from.

  • gh-159998: Fix libpython.dynamic in the PEP 739 build-details.json file for macOS and iOS framework builds. It now points at the framework’s library instead of a nonexistent path under lib/.

  • gh-144942: Fix the macOS shared library and framework builds not linking the libraries required by built-in modules, such as the HACL* objects needed by _blake2 when it is built in via Modules/Setup.local.

  • gh-143632: Fix the check that disables PR_SET_VMA_ANON_NAME on musl libc: it tested an unset variable, so it never had any effect and the build could fail with a redefinition of struct prctl_mm_map.

  • gh-131999: Platform support for Apple’s tvOS, watchOS and visionOS was added.

  • gh-153195: The PEG parser generator now supports splitting a grammar into several files with the @include meta, and generates a separate C file for the rules of each included file. The rules for specialized syntax errors moved from Grammar/python.gram to Grammar/invalid.gram, which generates the new Parser/parser_invalid.c.

  • gh-159819: Fix the shell version of python3-config (used on all POSIX platforms except macOS) when the installation prefix contains spaces or other characters special to the shell or sed: it printed an empty --prefix and wrong --includes/--ldflags paths while exiting successfully. The script now also exits with status 1 if it cannot determine its installation prefix.

  • gh-54767: The --enable-loadable-sqlite-extensions=no and --disable-loadable-sqlite-extensions configure options now disable loadable SQLite extensions instead of enabling them.

  • gh-159759: Fix the libpython.static path in PEP 739 build-details.json, which pointed to a file that is not installed when building with --enable-shared, and no longer list a static library for framework builds, which do not install one.

  • gh-75382: Make configure fail early with a clear error when a --with-*-sanitizer option is used but a program cannot be linked with the corresponding -fsanitize flag, for example because the sanitizer runtime library is not installed.

  • gh-159440: The version string reported by sys.version no longer carries a spurious -dirty suffix when CPython is built out-of-tree from a clean git checkout: the build stamp now checks the source tree instead of the build directory.

  • gh-157949: Remove dead build and preprocessor code for SCO UnixWare, OpenUNIX, SCO OpenServer and ReliantUNIX.

  • gh-157354: Fix the --with-name-sanitizer=no and --without-name-sanitizer configure options enabling the sanitizer instead of disabling it.

  • gh-156780: Emscripten libpython.a can now be linked into a program statically.

  • gh-155813: On macOS, LIBFFI_CFLAGS and LIBFFI_LIBS are no longer ignored when the SDK provides libffi, so ctypes can again be built against a different libffi. Patch by Advit Arora.

Windows

  • gh-160239: Remove dead and broken _repr_info() methods from asyncio.windows_events; they called Future._repr_info(), which no longer exists.

  • gh-159880: Fix a key handle leak in winreg.CreateKey(), winreg.CreateKeyEx() and winreg.OpenKey() when the winreg.OpenKey/result audit hook fails.

  • gh-159118: Fix a crash (RPC_NT_INTERNAL_ERROR) and intermittent window class failures in _wmi under high concurrency and load by initializing COM as multi-threaded (MTA) instead of apartment-threaded (STA).

  • gh-157418: Correct the third parameter name of IocpProactor.recvfrom_into() from flags to nbytes to reflect that it specifies the number of bytes to receive.

macOS

  • gh-159739: Propagate errors that occur while converting macOS system proxy settings.

WASI

IDLE

  • gh-161477: Fix repr() of idlelib.redirector.WidgetRedirector and idlelib.redirector.OriginalCommand, which displayed a spurious one-element tuple.

  • gh-159517: Fix the completion list and the call tip grabbing the focus on macOS with Tcl/Tk 9.1.

Ferramentas/Demos

  • gh-87613: Extend Argument Clinic O protocolo vectorcall to support Tipos no heap with zero argument construction.

  • gh-114258: Argument Clinic now supports the __next__ type slot (tp_iternext), including @critical_section.

  • gh-159385: iOS builds can now be configured to generate free-threading or debug output.

  • gh-131725: Tools/i18n/msgfmt.py now writes a hash table to the generated .mo file, as GNU msgfmt does.

API C

Python 3.16.0 alpha 1

Release date: 2026-10-13

Segurança

  • gh-158446: Corrige uma falha ou saída incorreta que poderia ocorrer ao formatar um float ou complex com uma precisão próxima ao INT_MAX da plataforma. A função PyOS_double_to_string() agora levanta uma ValueError para qualquer precisão dessa magnitude, independentemente do tipo de apresentação ou do valor, assim como os analisadores de string de formato já faziam para precisões acima de INT_MAX.

  • gh-156793: asyncio: loop.start_tls() e loop.create_connection() agora valida o argumento server_hostname se um ssl.SSLContext for passado com check_hostname definido com True.

  • gh-156793: ssl.SSLContext.wrap_bio() agora valida seus argumentos server_side, server_hostname e session similares a ssl.SSLContext.wrap_socket().

    Em particular, um contexto com check_hostname habilitado e sem que um server_hostname seja passado para wrap_bio() agora levanta uma ValueError em vez de concluir um handshake que verificava a cadeia de certificados sem verificar a identidade da outra parte, sem qualquer indicação de que a verificação havia sido ignorada.

  • gh-157265: Em tarfile, quando a extração de um link recorre à extração de um membro do arquivo, o membro deve ser ignorado se a função de filtro retornar None ao ser chamada com o nome do membro extraído substituído pelo nome do link.

  • gh-157953: Atualiza o libexpat empacotado para a versão 2.8.5.

  • gh-156002: Limita a quantidade de dados que o zipfile descompacta por leitura para membros compactados com bzip2, LZMA ou Zstandard, correspondendo ao limite existente para deflate. Um pequeno membro de arquivo podia anteriormente se expandir em uma alocação ilimitada, mesmo quando lido em pequenos pedaços.

  • gh-157579: Corrige uma condição de corrida na limpeza de tempfile.TemporaryDirectory. Ao contornar erros de permissão do sistema de arquivos, os arquivos agora são removidos com base em descritores de arquivo de diretórios abertos, em vez de resolver novamente seus caminhos; assim, a substituição de um diretório da árvore por um link simbólico não pode mais fazer com que a limpeza exclua arquivos fora do diretório temporário. Isso soluciona a CVE 2026-12345.

  • gh-155999: Corrige os filtros de extração tar e data do tarfile criando diretórios fora do destino para membros cujo nome sai do destino e retorna a ele, como ../evil/../dest/sub/file. A verificação de contenção usava o caminho resolvido, mas diretórios intermediários eram criados a partir do nome como fornecido.

  • gh-156293: Corrige uma falha no ssl que ocorria quando um sni_callback alternava uma conexão para outro SSLContext e o contexto que continha a função de retorno deixava de ser referenciado pela aplicação. Servidores que mantêm ativo o contexto do seu sni_callback (o caso habitual, quando ele encapsula o socket de escuta ou está armazenado no objeto do servidor) não foram afetados. Isso soluciona a CVE 2026-19445.

  • gh-155292: Altera o módulo stringprep e o codec encodings.idna para não considerar atributos de pontos de código Unicode além daqueles definidos na RFC 3454.

  • gh-155694: Corrige a CVE 2026-15806 restringindo as credenciais do HTTPPasswordMgr ao esquema da URL, evitando que credenciais armazenadas para uma URL HTTPS sejam usadas para uma URL HTTP correspondente, enquanto URIs sem esquema continuam a corresponder a qualquer esquema.

  • gh-153030: Corrigida a complexidade quadrática na análise incremental de construções longas não terminadas (como tags ou comentários) no html.parser.HTMLParser, que poderia ser explorada para uma negação de serviço.

  • gh-152674: Os métodos de xml.etree.ElementTree.Element: findall(), iterfind() e find() evitam comportamento quadrático ao usar predicados de índice XPath ([1], [last()], [last()-N]) em documentos XML com muitos irmãos de mesma tag.

  • gh-152216: Atualiza o libexpat empacotado para a versão 2.8.2.

  • gh-151987: O método tarfile.TarFile.extract() agora aplica o filtro fornecido quando extrai um alvo de link do arquivo como reserva (fallback).

  • gh-151981: No tarfile, a busca (seeking) em um fluxo agora para quando o fim do fluxo é atingido.

  • gh-151544: Modules/Setup.local não é mais usado como um ponto de referência para descobrir se o Python está rodando em uma árvore de código-fonte, pois poderia afetar potencialmente instalações reais. O arquivo pybuilddir.txt é agora o único indicador de execução em uma árvore de código-fonte.

  • gh-151558: Corrigida uma vulnerabilidade nos filtros de extração data e tar do tarfile onde arquivos manipulados podiam criar um link simbólico apontando para fora do diretório de destino. Esta foi uma desvio da CVE 2025-4330.

  • gh-150599: Corrige um possível estouro de buffer de pilha (stack buffer overflow) no bz2 quando um bz2.BZ2Decompressor é reutilizado após um erro de descompressão. O descompressor agora se torna inutilizável depois que a libbz2 relata um erro.

  • gh-150743: O http.client agora limita o número de linhas de cabeçalho final de resposta em blocos (chunked-response trailer lines) que ele lerá para max_response_headers (100 por padrão), e o número de respostas intermediárias (1xx) que ele pulará para 100. Um servidor malicioso ou quebrado podia anteriormente transmitir linhas de cabeçalho final ou respostas 100 Continue para sempre, travando o cliente mesmo quando um limite de tempo de socket estava em uso. Relatado por @YLChen-007 via GHSA-w4q2-g22w-6fr4.

  • gh-149835: shutil.move() agora resolve links simbólicos via os.path.realpath() ao verificar se o destino está dentro do diretório de origem, impedindo um desvio dessa proteção baseado em link simbólico.

  • gh-149698: Atualiza o libexpat empacotado para a versão 2.8.1 para a correção da CVE 2026-45186.

  • gh-87451: The ftplib module’s undocumented ftpcp function no longer trusts the IPv4 address value returned from the source server in response to the PASV command by default, completing the fix for CVE 2021-4189. As with ftplib.FTP, the former behavior can be re-enabled by setting the trust_server_pasv_ipv4_address attribute on the source ftplib.FTP instance to True. Thanks to Qi Deng at Aurascape AI for the report.

  • gh-149474: Corrige o escritor binário em profiling.sampling não disparando a auditoria (PEP 578) ao criar o arquivo de saída. O escritor e o leitor agora aceitam qualquer objeto caminho ou similar. Patch por Maurycy Pawłowski-Wieroński.

  • gh-149486: tarfile.data_filter() agora valida alvos de link usando o mesmo valor normalizado que é gravado no disco, remove separadores finais do nome do membro ao resolver o diretório de um link simbólico e rejeita membros de link que substituiriam o próprio diretório de destino. Isso fecha vários desvios de travessia de caminho do filtro de extração data.

  • gh-149079: Corrige uma potencial negação de serviço em unicodedata.normalize(). A etapa de ordenação canônica da normalização Unicode usava uma ordenação por inserção de tempo quadrático para reordenar caracteres combinantes, que poderia ser explorada com uma entrada manipulada contendo muitos caracteres combinantes em ordem não-canônica. Substituída por uma ordenação por contagem de tempo linear para sequências longas.

  • gh-149018: Proteção melhorada contra ataques de inundação de hash XML (XML hash-flooding) em xml.parsers.expat e xml.etree.ElementTree quando o Python é compilado com libExpat 2.8.0 ou posterior.

  • gh-143927: Normaliza todas as terminações de linha (CR, CRLF e LF) para LF+TAB ao escrever valores multilinha do configparser.

Núcleo e embutidos

  • gh-159285: Fix a crash in a debug build when copying an empty dict fails with MemoryError. Patch by Christian Aurich Zanettini Martins.

  • gh-129724: Fix the output of marshal for compiled code, and so the content of .pyc files, varying with what was imported or compiled earlier in the process. Strings in slice constants made only of ASCII letters, digits and underscores are now interned in the default build, like those of other constants.

  • gh-159137: Speed up the garbage collector by untracking tuples and counting the surviving objects while it looks for unreachable objects, which saves two walks of the collected generation in every collection.

  • gh-159137: Avoid a second reachability analysis in the garbage collector when no weakref callback, finalizer, or collectable-object debug output ran. Finished generators, coroutines, and async generators can skip this analysis even when finalized. Free-threaded builds also avoid a second stop-the-world pause in this case.

  • gh-158918: Reduce C stack usage of _PyModule_IsPossiblyShadowing, which could potentially cause stack overflows during module attribute access while deeply recursing in agressively optimized builds.

  • gh-158803: Fix a crash in bytes.join() and bytearray.join() in the free-threaded build when another thread concurrently mutates the list being joined. Patch by Christian Aurich Zanettini Martins.

  • gh-158824: Fix module-level __getattr__() being called before a module’s own lazy imports were resolved, which allowed it to shadow them.

  • gh-158820: Fix a crash when a lazy import is declared or resolved by a finalizer running during interpreter shutdown.

  • gh-158592: Skip the array reallocation when shrinking a small list. Patch by Donghee Na.

  • gh-158790: Speed up list.insert() and item deletion via del in free-threaded builds by using memmove(3).

  • gh-130706: Add a fast path to _Py_Dealloc() for non-GC objects. Patch by Donghee Na.

  • gh-158583: bytes.fromhex() and bytearray.fromhex(): Fix uninitialized memory read. Patch by Victor Stinner.

  • gh-158592: del list[index] now triggers shrinking the list’s internal array.

  • gh-158140: Resolve submódulos irmãos importados de forma preguiçosa (lazy) e de maneira independente, de modo que acessar um não importe outro apenas porque sua declaração apareceu por último.

  • gh-158316: On Free Threading, speed up bytearray.decode() by decoding the underlying storage directly instead of going through the buffer protocol.

  • gh-158486: Fix the PowerSort mask calculation in list.sort() for very large lists.

  • gh-158380: Fix incorrect type guards for dict reads and writes in the experimental JIT.

  • gh-158364: Corrige uma falha que ocorria quando sys._current_frames() ou sys._current_exceptions() eram chamados enquanto outro interpretador estava em execução.

  • gh-158219: Fix bytearray constructor: do not use a bytes object if its hash value is already computed. Patch by Cody Maloney and Victor Stinner.

  • gh-158241: Fix a crash and possible code object corruption following a MemoryError while compiling Python code.

  • gh-158254: Iteradores reversos sobre um dict e suas visualizações agora levantam RuntimeError se as chaves do dicionário forem alteradas durante a iteração — assim como os iteradores diretos —, em vez de fornecerem entradas para as novas chaves.

  • gh-158165: Fix compilation of _Py_get_machine_stack_pointer() with MinGW on Windows. Patch by Donghee Na.

  • gh-158072: Fix a JIT crash when a class is instantiated with their default arguments

  • gh-153569: Correct missing-brace error messages for multiline f-strings and t-strings. Improve tokenization of UTF-8 input split across many readline calls. Preserve source order when reading files with stateful encodings. Preserve input errors when scanning string literals.

  • gh-157914: Reverte gh-146064. A alteração relacionada ao PyMutex estava causando uma regressão significativa de desempenho em alguns casos.

  • gh-157838: Mescle contagens de referências enviesadas em nome de threads desvinculadas (detached) em vez de aguardar que elas se vinculem novamente, na construção com threads livres.

  • gh-157840: Speed up calls to hasattr() and three-argument getattr() for unassigned attributes in an object’s __slots__ by roughly 6x.

  • gh-157833: Fix call specialization for C functions and methods with METH_CLASS, METH_STATIC, or METH_COEXIST flags, improving their call performance.

  • gh-157778: Inclui o número da linha da chave de abertura na SyntaxError para um campo de substituição de f-string ou t-string não fechado, quando uma aspa correspondente em uma linha posterior for interpretada como o início de uma string não terminada.

  • gh-157468: Fix the JIT optimizer folding a builtin name to a constant taken from the interpreter’s builtins dictionary even when the running function uses a different __builtins__ mapping, such as one created with vars(builtins).copy(). The optimizer now only folds when the function’s builtins is the interpreter’s, and the folded constant is guarded at runtime so that another function sharing the same code object but a different builtins mapping does not use it.

  • gh-157757: Corrige um import a.b as c preguiçoso que lia b a partir de a em vez de importar o módulo a.b. Agora, ele associa o submódulo e levanta uma exceção ModuleNotFoundError quando não há um módulo correspondente ao nome.

  • gh-155695: Nomes resolvidos agora são removidos de sys.lazy_modules de forma mais consistente: uma importação preguiçosa (lazy import) de um módulo já carregado não é mais registrada, e a materialização de lazy from pkg import attr agora descarta a entrada pkg.attr.

  • gh-155742: In debug mode at Python exit, check if immutable singleton objects have been modified by mistake to detect bugs in C extensions. Patch by Victor Stinner.

  • gh-156939: When Python is built in debug mode, bytes and bytearray destructors now check if the trailing null byte has been overridden to detect buffer overflow. Patch by Victor Stinner.

  • gh-153568: Speed up parsing by reusing memoized rule prefixes across consecutive grammar alternatives, avoiding repeated rule calls and cache lookups.

  • gh-153568: Speed up parsing by sharing expression rules with assignment and deletion targets, and simplify comparison and keyword argument rules.

  • gh-157378: Corrige SyntaxError.offset e SyntaxError.end_offset para o erro “Non-UTF-8 code starting with …” quando um caractere não ASCII precede o byte inválido na mesma linha. Patch por Shamil Abdulaev.

  • gh-156762: Correção de comportamento indefinido em operator.methodcaller: a função do slot tp_clear retornava void em vez de int, fazendo com que o coletor de lixo a chamasse por meio de um tipo de função incompatível. Patch por Shamil Abdulaev.

  • gh-157377: Corrige gc.get_count() na construção com threads livres: a função estava reiniciando o contador de alocação local da thread que agenda a coleta de lixo automática. Uma thread que a chamasse durante uma alocação poderia impedir que lixo cíclico fosse coletado.

  • gh-157361: Implement anext() in Python instead of C, in a frozen _pybuiltins module. The awaitable returned by anext(it, default) is now a plain coroutine, so introspection tools such as asyncio.print_call_graph() can see through it into __anext__().

  • gh-153568: Reduce temporary allocations while parsing Python source.

  • gh-157247: Corrige sys.activate_stack_trampoline() permitindo a ativação a partir de um subinterpretador enquanto o JIT está habilitado no interpretador principal.

  • gh-157242: If bytearray.resize() or bytearray.take_bytes() fails, leave the bytearray unchanged, instead of clearing it. Patch by Victor Stinner.

  • gh-156995: Corrigido o problema em que um bytearray compartilhava seu buffer com um objeto bytes de um único byte e de mesmo valor, fazendo com que a escrita no bytearray modificasse aquele objeto bytes. Isso ocorria com bytearray.take_bytes() quando restava exatamente um byte e, na construção com threads livres, quando um bytearray era reduzido para um único byte a partir de outra thread.

  • gh-156910: Corrige um impasse na construção com threads livres ao definir __abstractmethods__ em um tipo enquanto outra thread detém a trava do tipo.

  • gh-156942: marshal no longer replaces the exception raised while marshalling the value with a generic ValueError("unmarshallable object"). Error messages now name the type of the unsupported object and, for the types supported only by newer data formats, the required version.

  • gh-156091: Fix a crash when compiling deeply nested inlined list, set, or dict comprehensions. A SyntaxError is now raised when the nesting exceeds the compiler’s static block limit.

  • gh-156865: Raise ValueError’s for overflows, while trying to change memoryview elements with 'f' and 'Zf' format codes. Patch by Sergey B Kirpichev.

  • gh-156894: Corrige a posição de erros de sintaxe que abrangem um intervalo, caso a linha contenha caracteres não ASCII antes do erro.

  • gh-156886: Fix ZeroDivisionError spuriously raised for a complex power with a non-zero base when the phase of the result is infinite, e.g. 1e300**1e308j or complex('inf')**1j.

  • gh-155525: Corrige a tokenização de tempo quadrático de módulos que contêm muitas f-strings ou t-strings.

  • gh-156689: Corrige uma leitura fora dos limites em compile() e ast.parse() quando um objeto AST é passado com mode='func_type'.

  • gh-156459: Fix cleanup on error in compiler_set_qualname. Previously it was called in _PyCompile_EnterScope, after the scope had been entered, and this was not reversed in case of an error.

  • gh-155725: tracemalloc não adquire mais a GIL nem cria um estado de thread temporário para rastrear alocações de memória: quadros de traceback agora armazenam strings UTF-8 simples em vez de objetos str do Python, e tracebacks são capturados usando o estado de thread Python já associado à thread chamadora, mesmo se ela não estiver anexada. Threads sem um estado de thread Python registram o traceback como <unknown>.

  • gh-156371: Fix missing PyRefTracer_DESTROY events for trashcan deferred objects. Patch by Donghee Na.

  • gh-156310: Fix memory safety issues in the iter() fallback for objects that implement __getitem__() without __iter__() (PySeqIter_Type). Sharing an iterator between threads in the free-threaded build could use the underlying sequence after it was freed, and re-entrant exhaustion in the default build could decrement the sequence’s reference count twice. Concurrent iteration may still see duplicate or missing items, but it no longer corrupts the interpreter state.

  • gh-64862: The iter() function now accepts the stop_exception parameter. The created iterator stops when the callable raises the specified exception. The second parameter is now named stop_value and can be passed by keyword. aiter() now accepts the same stop_value and stop_exception parameters, calling an asynchronous callable and awaiting the result.

  • gh-156114: Corrige uma falha no trampoline do perf quando um objeto código possui um nome ou nome de arquivo que não pode ser codificado em UTF-8. Correção feita por Shamil Abdulaev.

  • gh-156204: Fix a crash in PyErr_GivenExceptionMatches() when evaluating deeply nested exception tuples. The recursion is now bounded, and exceeding the limit is reported as an unraisable exception.

  • gh-148750: encodings não é mais congelado, devido a problemas ao importar submódulos ao usar uma biblioteca padrão compactada em zip.

  • gh-156126: Corrige uma falha ao importar um módulo cujo nome contém caracteres que não podem ser codificados em UTF-8 (como surrogates isolados) enquanto -X importtime está habilitado.

  • gh-144446: Fix thread safety of the generator.gi_frame, coroutine.cr_frame and agen.ag_frame attributes in the free-threading build.

  • gh-156021: Empty AST node representations no longer include ... when the recursion depth limit is exceeded, making them easier to distinguish from non-empty ones. Patch by Bartosz Sławecki.

  • gh-155254: Evita aviso sobre biblioteca padrão ausente ao usar Arquivos _pth.

  • gh-155978: Corrige um vazamento de memória na construção com threads livres ao definir ou excluir um método especial (como __repr__) em uma classe que possui muitas subclasses.

  • gh-148653: Forbid marshalling recursive tuples, and fix a crash when unmarshalling a self-referencing tuple.

  • gh-155823: Fix a JIT bug where the side exit taken when a virtual iterator is exhausted left a stale value on the stack, so the tier one interpreter resumed with corrupted state and yield from raised AttributeError instead of finishing normally.

  • gh-155141: Compile pure-keyword calls with 16 to 29 keyword arguments using the faster CALL_KW instruction. This includes common cases such as dataclass constructors with many fields.

  • gh-155752: Corrige um travamento quando um argumento de types.GenericAlias ganha um gancho __typing_subst__ após os parâmetros do apelido terem sido armazenados em cache.

  • gh-155504: Fix a crash when thread state creation fails before the thread state is fully initialized.

  • gh-155526: Corrige um OverflowError espúrio para abs(nanj) caso errno tenha sido definido anteriormente como ERANGE por alguma chamada de biblioteca. Patch por Sergey B Kirpichev.

  • gh-129752: Não atualiza contadores adaptativos na construção com threads livres quando o bytecode local de thread está desativado (-X tlbc=0). Patch por Donghee Na.

  • gh-155515: Rastreia os iteradores internos do HAMT, que dão suporte à iteração sobre um contextvars.Context, com o coletor de lixo. Um ciclo de referência passando por tal iterador nunca era coletado, vazando todo o contexto sobre o qual iterava.

  • gh-155400: Corrige um impasse (deadlock) na construção com threads livres entre duas threads atribuindo a um método especial da mesma classe. Ao aplicar as atualizações de slot de tipo com o mundo parado (stop-the-world), apenas a trava de tipo era impedida de ser liberada; o mutex do dicionário do tipo ainda podia ser liberado e readquirido, na ordem incorreta, se a thread bloqueasse no mutex do stop-the-world.

  • gh-155315: Fix marshal so that a frozendict referenced more than once in the serialized data round-trips correctly, instead of failing to load with ValueError. Patch by tonghuaroot.

  • gh-155363: Corrige um vazamento na construção com threads livres quando a criação de um estado de thread falha após um slot QSBR interno ter sido reservado para ele. O slot nunca podia ser recuperado, fazendo com que a matriz QSBR crescesse sem limites em falhas repetidas.

  • gh-154701: Corrige um laço infinito no JIT quando uma saída lateral de FOR_ITER vincula um executor de volta a si mesmo.

  • gh-154937: Fix a data race on thread handle identifiers when _thread._shutdown() runs concurrently with the startup of non-daemon threads in the free-threaded build.

  • gh-120321: Fix thread safety of asynchronous generators when iterated, closed or thrown into concurrently from multiple threads on the free threading build. Also make an athrow() awaitable single-use: reusing it after completion now raises RuntimeError instead of resuming the generator again.

  • gh-154902: Corrige uma falha quando __conditional_annotations__ é reatribuído a um objeto que não é um conjunto.

  • gh-151464: Exclui o token inválido <> da saída de tokenize. SyntaxError para <> agora sugere !=.

  • gh-133931: Corrige condições de corrida de dados ao definir atributos de objetos de função na construção com threads livres.

  • gh-154719: Espaços em branco ao final de uma expressão de interpolação em t-string agora são preservados em string.templatelib.Interpolation.expression, até o } de fechamento ou até o delimitador de conversão (!), formatação (:) ou depuração (=). Continuações de linha explícitas após um = de depuração permanecem como parte do texto de depuração e são excluídas de expression.

  • gh-154775: Ao corresponder um literal complexo em instruções case, um sinal + estranho (por exemplo, 1++1j ou 1-+1j) não é mais permitido.

  • gh-154709: Corrige um acesso fora dos limites em iteradores reversos de dicionário quando o dicionário subjacente é limpo e modificado após a criação do iterador.

  • gh-154695: Corrige asyncio.Task levantando AttributeError quando criada com eager_start=True e sem argumento loop explícito.

  • gh-154044: Fix a data race on a descriptor’s __qualname__ cache in the free-threaded build.

  • gh-154196: Melhora as mensagens de AttributeError de importações preguiçosas (lazy imports) não resolvidas. Patch por Bartosz Sławecki.

  • gh-153809: Corrige falha do interpretador ao desalocar objetos de asyncio.Task em construções com threads livres. Contribuição de Sergey Miryanov.

  • gh-154429: Slightly speed up deallocation of objects that are not tracked by the garbage collector, such as int, float and str.

  • gh-145868: Suggest the closest valid feature name in the SyntaxError message when an unknown name is imported from __future__.

  • gh-154275: Corrige uma falha ao obter __parameters__ profundamente aninhados de objetos types.GenericAlias.

  • gh-154043: Fix a data race when iterating a shared types.GenericAlias iterator from multiple threads under the free-threaded build.

  • gh-154014: Corrige uma asserção do JIT durante o encerramento do interpretador inicializando campos vm_data para executores frios que ignoram _Py_ExecutorInit().

  • gh-153932: Corrige problema de segurança de thread no método __reduce__ do enumerate.

  • gh-153881: Corrige potencial corrida de dados ao chamar __getstate__() sob a construção com threads livres.

  • gh-153785: AttributeError: The default error message is now generated from name and obj attributes when both are set and the exception was constructed with no positional arguments, or with a single positional argument equal to name. Patch by Bartosz Sławecki.

  • gh-152075: Reduced lock contention during LOAD_GLOBAL bytecode specialization under free threading.

  • gh-78959: Add the order parameter to memoryview.cast(). With order='F' it creates a zero-copy Fortran-contiguous (column-major) view of a flat buffer, mirroring the order argument of memoryview.tobytes().

  • gh-153568: Speed up the tokenizer by copying source text verbatim when it contains no carriage returns.

  • gh-153578: Fix an out-of-bounds write in bytearray.extend() when the bytearray is resized while the argument’s __buffer__() is being acquired, for example by another thread. Patch by tonghuaroot.

  • gh-153570: Corrige um uso-após-liberação (use-after-free) em bytearray.take_bytes() quando o método __index__() do argumento redimensiona o bytearray. Patch por tonghuaroot.

  • gh-153568: Speed up the parser by caching repeated identifiers during a parse.

  • gh-153568: Speed up the parser by not materializing the text of tokens whose text is never read.

  • gh-153568: Speed up parsing of left-recursive rules by updating their memoization entries in place.

  • gh-153568: Speed up the parser by turning its per-rule C-stack check into a single inline comparison.

  • gh-153568: Speed up the parser by letting memoization lookups that cannot match return immediately.

  • gh-153419: Corrige múltiplas falhas e vazamentos de referência em bytearray causados por ignorar o __init__() e código de configuração de estado quebrado.

  • gh-153354: Fix a crash in compiler-generated __annotate__ functions when the annotation format comparison returned a non-boolean result.

  • gh-153298: Corrige uma corrida de dados na inicialização dos __parameters__ de types.GenericAlias em construções com threads livres.

  • gh-153205: Corrige um potencial SystemError durante chamadas vetoriais quando a alocação de memória falha. Um MemoryError agora é levantado em seu lugar.

  • gh-153171: Improve syntax error messages for misplaced not after an operator in contexts where a generic “invalid syntax” error was previously reported, such as 1 << 2 + not x and 1 * + not x.

  • gh-153236: Propaga exceções levantadas ao importar submódulos preguiçosos em vez de relatá-las como atributos ausentes.

  • gh-102960: Frame objects now support weak references. Patch by Łukasz Langa.

  • gh-152708: Corrige a assimetria na geração da AST em que o operador unário positivo + era implicitamente descartado em expressões de correspondência de padrões, restaurando a paridade de análise sintática com o operador unário negativo -.

  • gh-152682: Corrige desreferência de ponteiro NULL em compile() quando um nome reservado (por exemplo, __classdict__) é usado como nome de parâmetro de tipo e a alocação de memória falha ao formatar a mensagem de erro.

  • gh-152635: Corrige uma falha causada ao ficar sem memória ao criar um canal _interpchannels. Agora uma exceção MemoryError é levantada corretamente.

  • gh-152405: Não expõe o mapeamento interno de types.MappingProxyType ao realizar operações de comparação rica com tipos fora da biblioteca padrão. Anteriormente, era possível mutar o mapeamento interno de um proxy lá. Agora passamos não a instância original de dict, mas sua cópia, ao lidar com tipos personalizados.

  • gh-152492: O método update de collections.OrderedDict agora pode aceitar frozendict como argumento.

  • gh-152375: Corrige comportamento indefinido quando uma função de retorno do sys.monitoring levantava uma exceção enquanto o programa estava seguindo um desvio ou laço.

  • gh-152192: Fix a truncated oparg being passed to JIT trace initialization for a JUMP_BACKWARD with an EXTENDED_ARG.

  • gh-152235: Adia o rastreamento pelo GC de set.intersection(), set.difference(), set.symmetric_difference(), set.union() e set.__sub__. Patch por Donghee Na.

  • gh-152315: TypeError messages for some instance methods called with too many positional arguments now suggest checking whether the method definition is missing the self parameter.

  • gh-152235: Adia o rastreamento pelo GC de um set ou frozenset para o final de sua construção a partir de um iterável. Patch por Donghee Na.

  • gh-152228: Corrige uma falha de asserção quando o python é construído em modo de depuração que acontecia em str.replace() sob uma situação de memória limitada.

  • gh-152107: Fix a crash when creating a dict item iterator (for example iter(d.items()) or reversed(d.items())) under a memory-allocation failure. Patch by Jiucheng Zang.

  • gh-151722: frozendict.fromkeys() agora só rastreia o frozendict no coletor de lixo depois que o dicionário está totalmente inicializado. Patch por Donghee Na e Victor Stinner.

  • gh-151763: Corrige possível falha na desalocação de types.CodeType.

  • gh-152020: Na construção com threads livres, asyncio.all_tasks() não perde mais tarefas iniciadas de forma antecipada (eager) quando chamado a partir de uma thread diferente daquela que executa o laço de eventos.

  • gh-151763: Corrige uma potencial falha em compile(), exec(), eval() e ast.parse() quando uma alocação falha: o analisador ou compilador podia retornar sem definir uma exceção.

  • gh-151912: Corrigida uma falha em type() ao selecionar uma metaclasse cujo slot tp_new é NULL. Tais metaclasses agora são rejeitadas com TypeError em vez de causar uma desreferência de ponteiro NULL.

  • gh-151895: Fixed a crash in marshal.loads() when an allocation failed while loading a reference-tracked dictionary; it now raises MemoryError.

  • gh-151905: Corrige o tratamento de erro de falta de memória (OOM) em PyFrame_GetBack() para propagar exceções em vez de mascará-las como None.

  • gh-151907: Avoid creating list objects in comprehensions when the comprehension is not used as a value.

  • gh-151773: Corrige uma falha em contextvars.ContextVar.set() quando a alocação de memória falha.

  • gh-151665: inspect.signature() agora funciona em avaliadores preguiçosos de aliases de tipo e parâmetros de tipo em vez de levantar ValueError.

  • gh-151672: Corrige uma inconsistência onde chamar __lazy_import__ com uma string fromlist retornava um types.LazyImportType que se resolve para o membro nomeado, em vez do módulo sendo importado.

  • gh-151722: Adia o rastreamento pelo GC de frozendict para o final da construção. Patch por Donghee Na.

  • gh-151619: Corrige um problema onde o uso de espaços de nomes globais ou embutidos não de módulo (como dicionários passados para exec()) podia fazer com que cargas globais em cache produzissem importações preguiçosas não resolvidas.

  • gh-151646: Fix a data race in free-threading builds between gc.get_stats() and a concurrent garbage collection cycle. Access to the per-generation statistics is now serialized with a mutex so the reader observes a consistent snapshot.

  • gh-151126: Corrige uma falha ao compartilhar objetos memoryview entre interpretadores que falha devido à falta de memória. Agora levanta um MemoryError adequado.

  • gh-151644: Corrige uma corrida de dados em sys.setdlopenflags() e sys.getdlopenflags() quando chamados concorrentemente na construção com threads livres. As funções subjacentes _PyImport_GetDLOpenFlags e _PyImport_SetDLOpenFlags agora usam operações atômicas de carga/armazenamento.

  • gh-151126: Evita possível falha no _winapi.c onde um dispositivo não tem mais memória. Agora ele levanta adequadamente um MemoryError. Patch por Ivy Xu.

  • gh-151126: Avoid possible crash in getpath.c where a device has no memory left. Now it properly raises a MemoryError. Patch by Ivy Xu.

  • gh-151518: Fix a free-threaded stop-the-world fairness issue that could starve a thread reattaching after being suspended while detached.

  • gh-151546: Corrige a verificação do limite da pilha se o Python estiver vinculado à musl (ex: Alpine Linux). Usa o tamanho da pilha definido pelo ligador (linker) para calcular os limites da pilha. Patch por Victor Stinner.

  • gh-151510: Corrige uma falha em __lazy_import__() quando chamado sem um argumento globals explícito e sem um quadro Python atual.

  • gh-151461: Corrige a execução direta de arquivos com codificações de origem inválidas para relatar a busca do codec subjacente ou erro de decodificação em vez da mensagem genérica SyntaxError: encoding problem. Patch por Bartosz Sławecki.

  • gh-151377: Corrige condições de corrida em construções com threads livres ao atualizar slots de tipo para classes recém-criadas e ao remover entradas do dicionário de subclasses de um tipo base.

  • gh-151218: PyConfig_Set() e sys.set_int_max_str_digits() agora substituem sys.flags (criam um novo objeto), em vez de modificar sys.flags no local (in-place). Patch por Victor Stinner.

  • gh-151297: Corrige uma desreferência de ponteiro inválida que podia ocorrer ao chamar PyObject_Realloc() com um ponteiro NULL em construções com threads livres ou com PYTHONMALLOC definido como mimalloc.

  • gh-151253: Se import encodings (primeira importação) falhar na inicialização do Python, descarrega a configuração do caminho do Python para ajudar os usuários a depurarem sua configuração. Patch por Victor Stinner.

  • gh-151238: Corrige uma falha ao compilar uma f-string ou t-string concatenada se ocorrer um erro ao processar uma de suas partes.

  • gh-151112: Corrige uma falha no compilador que podia ocorrer ao ficar sem memória.

  • gh-151126: Corrige uma falha quando não há memória restante em um dispositivo, que acontecia em: compilação de código, módulo _interpchannels, função _winapi.CreateProcess().

    Agora esses locais levantam erros MemoryError adequados.

  • gh-150902: Aplica uma otimização existente de PyCriticalSection (mutex único) para PyCriticalSection2: evita adquirir as mesmas travas que a CS atual já adquiriu.

  • gh-151065: Corrige vazamento de memória ao usar o alocador de memória mimalloc.

  • gh-151029: No Linux, corrige sys.remote_exec() incapaz de encontrar memória gravável remota quando libpython foi substituída no disco.

  • gh-150942: Speed up frame local variable item collection by appending result pairs to the output list without an extra reference-count round-trip (using the internal reference-stealing list append helper). Patch by Omkar Kabde.

  • gh-150988: Corrige um vazamento de referência em OSError quando atributos são definidos antes de super().__init__().

  • gh-145685: The internal method cache used for types is now a per-type cache instead of a global per-interpreter one, improving performance and reducing cache misses. Patch by Kumar Aditya.

  • gh-146495: Improve SyntaxError message for && and || operators, suggesting and/& and or/| respectively.

  • gh-148874: Ignores interrupções imediatamente após chamar o método __enter__ de um gerenciador de contexto em uma instrução with. Isso garante que o método __exit__ seja sempre chamado em uma instrução with.

  • gh-150459: Corrige mensagem de erro de SyntaxError para from x lazy import y. Levanta SyntaxWarning em from . lazy import x (com espaço em branco entre os pontos e um módulo chamado lazy).

  • gh-150858: Corrige uma corrida de dados ao alterar o __qualname__ de um tipo concorrentemente em construções com threads livres.

  • gh-150737: Optimize bytecode for empty unpack cases such as {*()}.

  • gh-150723: Corrige marcas de data/hora do perf jitdump no macOS. Os eventos eram marcados usando CLOCK_MONOTONIC, mas os perfiladores do macOS marcam suas amostras com mach_absolute_time(). A incompatibilidade impedia que os mapeamentos de código JIT se alinhassem com as amostras, então nenhum quadro Python podia ser resolvido.

  • gh-150723: Corrige IDs de thread malformados do perf jitdump no macOS. O campo thread_id do registro JR_CODE_LOAD era gravado como um valor de 64 bits em vez do valor de 32 bits exigido pelo formato jitdump, o que deslocava cada campo seguinte e impedia que os perfiladores resolvessem quadros Python.

  • gh-150700: Corrige um SystemError ao compilar uma compreensão de escopo de classe contendo um lambda que referencia __class__, __classdict__ ou __conditional_annotations__. Patch por Bartosz Sławecki.

  • gh-150633: Corrige o importador congelado aceitando nomes de módulos com bytes nulos embutidos, o que fazia com que ele ignorasse o cache do sys.modules e criasse objetos de módulo duplicados.

  • gh-144774: Corrige corrida de dados em BaseException quando uma exceção é copiada enquanto está sendo mutada.

  • gh-150411: Corrige uma corrida de dados na construção com threads livres quando gc.get_count() lê a contagem de alocação da geração jovem enquanto outra thread a atualiza.

  • gh-150374: Corrige a liberação dupla da trava de importação em erros de reificação de importação preguiçosa.

  • gh-148613: Corrige uma corrida de dados na compilação free-threaded entre gc.set_threshold() e o agendamento da coleta de lixo durante a alocação de objetos.

  • gh-149156: Corrige uma falha intermitente após os.fork() quando o perfilamento de trampolim do perf está ativado e o filho retorna através de quadros de trampolim herdados do processo pai.

  • gh-149449: Corrige uma falha de uso-após-liberação quando o módulo unicodedata era removido do sys.modules e coletado pelo GC entre chamadas que decodificam escapes \N{...} ou usam o tratador de erros do codec namereplace.

  • gh-150207: Corrige uma falha quando a alocação de memória falha durante a inicialização do tokenizador. Uma exceção MemoryError adequado é agora levantada em seu lugar.

  • gh-149816: Fix a Use-After-Free race condition in subtype_getweakref() during concurrent weakref creation and destruction in the free-threading build.

  • gh-150107: asyncio: métodos de laço de eventos sendfile() e sock_sendfile() agora chamam file.seek(offset) se file tiver um método seek(), mesmo se offset for 0 (valor padrão).

  • gh-150208: Evite usar aspas duplas em valores de string provenientes de pyconfig.h nas variáveis de sysconfigdata.

  • gh-150146: Corrige uma falha em uma substituição de variável de tipo complexa.

    from typing import TypeVar; memoryview[TypeVar("")][*typing.Mapping[..., ...]] costumava falhar devido à verificação NULL ausente na chamada de função C _unpack_args.

  • gh-148587: sys.lazy_modules é agora um conjunto em vez de um dicionário, como originalmente especificado no PEP 810.

  • gh-150027: Improve performance of frozenset objects by avoiding copies during construction.

  • gh-150042: Corrige vazamento de referência em queue.SimpleQueue.put se a alocação de memória falhar.

  • gh-149590: Corrige falha quando o faulthandler é importado mais de uma vez.

  • gh-149816: Fix race conditions in invoke_gc_callback iterating gc.callbacks in free-threading mode.

  • gh-138325: Speed up converting a list to a tuple in the tuple(genexpr) fast path and in starred tuple displays (e.g. (*a, *b)) by stealing the list’s items into the tuple instead of copying them.

  • gh-149816: Corrige uma condição de corrida em _PyBytes_FromList no modo threads livres.

  • gh-157407: Argument Clinic now parses arguments of positional-only methods with a defining class directly, without a _PyArg_Parser.

  • gh-149816: Corrige uma condição de corrida no memoryview com free-threading.

  • gh-149807: Corrige hash(frozendict): calcula o hash de cada par (chave, valor) corretamente. Patch por Victor Stinner.

  • gh-149805: Corrige uma exceção SystemError ao compilar uma anotação de classe __classdict__. Encontrado por OSS-Fuzz no #512907042.

  • gh-149738: sqlite3: Disallow removing row_factory and text_factory attributes of a connection or cursor to prevent a crash on a query.

  • gh-139808: Adiciona proteções de ramificação para AArch64 (BTI/PAC) em código assembly usado por -X perf_jit (integração com o perfilador perf do Linux).

  • gh-127727: Warn when running a virtual environment created for a different minor Python version than the current interpreter, and suggest using python -m venv --upgrade.

  • gh-148871: The empty tuple () is now loaded via LOAD_COMMON_CONSTANT instead of LOAD_CONST, removing it from per-code-object co_consts tuples.

  • gh-149689: Corrige a propagação de erro ausente em auxiliares de ação do analisador quando a alocação de memória falha. Patch por Thomas Kowalski.

  • gh-149676: Corrige o hash de frozendict | frozendict.

  • gh-148829: Objetos sentinel agora oferecem suporte a um argumento repr= e seu atributo __module__ é gravável.

  • gh-149642: Permite importações dentro de chamadas exec() dentro de funções sob PYTHON_LAZY_IMPORTS=all.

  • gh-144957: Corrige importações preguiçosas no formato from de atributos do módulo fornecidos por __getattr__ em nível de módulo.

  • gh-149459: Corrige uma falha no otimizador JIT quando uma proteção LOAD_SPECIAL especializada desotimizou após inserir a entrada sintética de pilha NULL.

  • gh-149321: Não oferece suporte a none como modo de importação preguiçosa.

  • gh-149162: Corrige um potencial impasse (deadlock) em PyUnicode_InternFromString() e outras funções de estagioamento (interning) na construção com threads livres quando chamadas a partir de inicializadores locais estáticos do C++.

  • gh-148817: Dobra literais constantes grandes de listas e conjuntos usados como o iterável de um laço for ou teste in/not in em uma tuple ou frozenset constante, restaurando uma otimização feita anteriormente pelo otimizador AST que foi perdida quando a dobragem de constantes mudou para o CFG.

  • gh-148825: Corrige erro de construção se a especialização estiver desativada.

  • gh-148450: Corrige abc.register() para que ele invalide tags de versão de tipo para classes registradas.

  • gh-148442: Fix a race condition in list.__lt__, list.__le__, list.__gt__, and list.__ge__. Previously, under concurrent list mutation, the items being compared could be replaced with other objects before the final comparison, causing the final comparison result to be incorrect.

  • gh-75723: Avoid re-executing .pth files when site.addsitedir() is called for a known directory.

  • gh-145857: The DELETE_GLOBAL opcode is now replaced with PUSH_NULL; STORE_GLOBAL.

  • gh-145855: The DELETE_ATTR opcode is now replaced with PUSH_NULL; STORE_ATTR.

  • gh-145854: The DELETE_NAME opcode is now replaced with PUSH_NULL; STORE_NAME.

  • gh-138912: Add fast path for match class patterns without any sub-patterns to improve performance by ~15%.

  • gh-91484: memoryview.cast() now allows casting from N-D to 1-D for F-contiguous.

  • gh-128213: Speed up bytes creation from list and tuple of integers.

    Patch by Ben Hsing and Pieter Eendebak

  • gh-117999: Fix calculation of powers of complex numbers. Small integer powers now produce correct sign of zero components. Negative powers of infinite numbers now evaluate to zero instead of NaN. Powers of infinite numbers no longer raise OverflowError.

  • gh-85260: compile() agora levanta ValueError em vez de travar em uma construção de depuração se um campo identificador de um nó AST (como o nome de uma função, uma classe, um módulo importado ou uma exceção capturada) for "None", "True" ou "False".

  • bpo-38131: Produce more meaningful messages when compiling AST objects with wrong field values. Patch by Batuhan Taskaya.

Biblioteca

  • gh-159184: Fix marshal.dumps() raising TypeError for a set or frozenset containing several complex NaNs, which also made it impossible to write a .pyc file for source code containing such a constant.

  • gh-159185: Fix a crash in marshal.dumps() and marshal.dump() when a set is modified while its elements are serialized, for example by the __buffer__() method of one of its elements. RuntimeError is now raised.

  • gh-129724: Make the output of marshal.dumps() and marshal.dump(), and so the content of .pyc files, independent of the reference counts of the serialized objects. The format is unchanged, but the data is not byte-for-byte identical to that written by previous Python versions.

  • gh-87720: Fixed error in email new policies where header folding failed to detect the need to re-quote text obtained from encoded words in certain cases.

  • gh-158929: Fix crash when calling syslog.syslog() while a subinterpreter in another thread calls syslog.openlog() or syslog.closelog().

  • gh-158897: Optimize io.BufferedReader.readline() when lines are close to the buffer size (128 kB by default) or longer than the buffer size. Replace the C loop searching for the newline byte in the buffer with a memchr() call which is more efficient. In the good case, it makes readline() up to 4x faster! Patch by Victor Stinner.

  • gh-158936: dataclass() no longer fails when a string annotation names a lazy import that cannot be resolved, matching the behavior for non-string annotations.

  • gh-158893: Make os.strerror() thread-safe: use the reentrant strerror_r() function if available. Patch by Victor Stinner.

  • gh-158539: Fix macOS runtime section lookup for remote debugging when virtual memory region sizes differ from Mach-O segment file sizes.

  • gh-156545: Fix deep flamegraph exports on platforms with small C stacks by falling back to the Python JSON encoder when the C encoder runs out of stack space.

  • gh-79459: tempfile functions that take a prefix or suffix argument now raise a ValueError if they contain a directory component: tempfile.mkstemp(), tempfile.mkdtemp(), tempfile.TemporaryFile(), tempfile.NamedTemporaryFile().

  • gh-158552: Wait for Windows threads to finish suspending before reading target memory in the sampling profiler’s blocking mode. Resume the target if waiting for suspension fails.

  • gh-156321: Fix asyncio.shield() reporting an exception from the inner future through the loop exception handler as soon as it completes after the shield was cancelled, even when the exception is retrieved afterwards. The exception is now reported only if it is never retrieved, as with any other future.

  • gh-158539: Fix profiling.sampling exception mode discarding samples for code running inside an except block in a generator or coroutine. The remote debugger now follows tstate->exc_info and its previous_item chain instead of only reading the embedded exc_state, matching the exception that sys.exception() reports.

  • gh-158563: Fix turtle.undo() after turtle.teleport() and after an exception in turtle.circle(), turtle.dot() or turtle.write(). Fix turtle.stamp(), turtle.clearstamp(), turtle.clear() and turtle.reset() when the undo buffer is disabled.

  • gh-158540: Fix profiling.sampling not adding the directory containing the profiled script to sys.path, which prevented the script from importing modules placed next to it. The script’s directory is now added, matching the behavior of python script.py.

  • gh-158522: Fix profiling.sampling showing a single frame for a task whose coroutine recurses. Patch by Timofei Ivankov.

  • gh-158237: Fix ast.unparse() to not insert a space before attribute access on bool constants (e.g. True.real instead of True .real).

  • gh-158169: Fix zlib.Decompress.unconsumed_tail duplicating unused_data after end of stream when max_length was used.

  • gh-141540: Quote the unconverted data and the format in the error messages of time.strptime() and datetime.datetime.strptime() so that whitespace such as a trailing newline is visible.

  • gh-157788: Corrige a falha do comando python -m asyncio ps ao lidar com um processo que possui uma tarefa com nome superior a 255 caracteres.

  • gh-157605: Fix profiling.sampling failing when a native thread has an empty Python stack.

  • gh-157763: The undocumented ctypes.util.test() function is now soft deprecated and a no-op at runtime.

  • gh-157660: Corrige profiling.sampling relatando erros ou números de linha incorretos em construções com threads livres quando um array de bytecode local à thread aumenta de tamanho ou recebe novas entradas após ter sido armazenado em cache.

  • gh-153888: Fix unittest.mock.patch() with autospec, spec, or spec_set when used with lazy-imported objects.

  • gh-119646: On Windows, OSError from subprocess now includes the attempted executable or working directory in filename.

  • gh-157675: encodings.idna.nameprep() now takes a limit argument that allows rejecting extremely large input early. The idna encoding and the encodings.idna.ToASCII() and encodings.idna.ToUnicode() functions use this to avoid passing unbounded input to quadratic-time algorithms.

  • gh-157672: Corrige o tkinter no macOS: a criação de uma instância de Tk não substitui mais os manipuladores Python para SIGINT, SIGHUP e SIGTERM pelo manipulador do Tk que encerra o processo; assim, Ctrl-C volta a levantar KeyboardInterrupt.

  • gh-157639: Corrige uma falha no cProfile quando um temporizador externo reentra no perfilador. Eventos de perfilamento levantados enquanto o temporizador externo está em execução agora são ignorados.

  • gh-157621: Fix a crash when a weak-reference callback is attached to a typing.ParamSpecArgs or typing.ParamSpecKwargs instance.

  • gh-157633: Update unicodedata database to Unicode 18.0.0.

  • gh-69919: code.InteractiveInterpreter.runsource() and the REPL now report any exception raised by compiling the source, such as MemoryError or RecursionError for too deeply nested source, instead of propagating it or printing a traceback of the REPL internals.

  • gh-157514: Add constants tkinter.TCL_VERSION_INFO and tkinter.TK_VERSION_INFO, named tuples with the versions of the Tcl and Tk libraries that were used for building the module, and _tkinter.TCL_PATCH_LEVEL and _tkinter.TK_PATCH_LEVEL strings.

  • gh-157513: ssl.OPENSSL_VERSION_INFO is now a named tuple. Add ssl.OPENSSL_API_VERSION_INFO which provides information about the version of the OpenSSL library that was used for building the module.

  • gh-157487: Add constants ctypes.LIBFFI_VERSION, ctypes.libffi_version, ctypes.LIBFFI_VERSION_INFO and ctypes.libffi_version_info, which provide information about the version of the libffi library in use. They are only available with libffi 3.5 or later.

  • gh-157485: Add constants readline.READLINE_VERSION_INFO, readline.readline_version_info and readline.readline_version, which provide information about the version of the Readline library in use.

  • gh-157480: Add constants in dbm.ndbm which provide information about the version of the underlying library in use: GDBM_VERSION_INFO, gdbm_version_info and gdbm_version if it is GDBM, or BDB_VERSION, bdb_version, BDB_VERSION_INFO and bdb_version_info if it is Berkeley DB. dbm.ndbm.library is now 'ndbm' instead of 'GNU gdbm' for a classic NDBM library.

  • gh-157478: Add constants dbm.gnu.GDBM_VERSION_INFO, dbm.gnu.gdbm_version_info and dbm.gnu.gdbm_version, which provide information about the version of the GDBM library in use. The private constant _gdbm._GDBM_VERSION has been removed.

  • gh-157475: Add constants decimal.LIBMPDEC_VERSION, decimal.libmpdec_version, decimal.LIBMPDEC_VERSION_INFO, and decimal.libmpdec_version_info in the C implementation, which provide information about the version of the libmpdec library in use.

  • gh-157473: Add constant xml.parsers.expat.VERSION_INFO which provides information about the version of the Expat library that was used for building the module. xml.parsers.expat.version_info is now a named tuple.

  • gh-157470: Add constants sqlite3.SQLITE_VERSION and sqlite3.SQLITE_VERSION_INFO which provide information about the version of the SQLite library that was used for building the module. sqlite3.sqlite_version_info is now a named tuple.

  • gh-157451: Fix gettext plural form selection when the Plural-Forms expression combines the unary ! operator with a binary operator, for example !n + 1 or 2 * !n. The latter raised SyntaxError.

  • gh-150816: Speed up inspect.signature() for Python functions by skipping redundant validation when creating inspect.Parameter objects.

  • gh-157335: Corrige uma escrita fora dos limites em mmap.mmap.__setitem__ que poderia ocorrer quando a conversão do índice ou do valor atribuído (via __index__() para um único item, ou via protocolo de buffer para uma fatia) redimensionasse ou fechasse o objeto mmap durante a atribuição.

  • gh-157406: Corrige a implementação em Python de xml.etree.ElementTree.XMLParser: o método doctype() do destino agora é chamado para uma declaração de tipo de documento sem identificador externo, como <!DOCTYPE html>, assim como na implementação em C.

  • gh-128509: marshal.load() e marshal.loads() agora podem obter singletons de strings de 1 byte. Patch por Victor Stinner.

  • gh-157364: Fix a use-after-free in io.TextIOWrapper when a call to the underlying buffer reentrantly detaches it. Patched by Shamil Abdulaev.

  • gh-157366: Remove the accidental acceptance of bytes in the C implementation of xml.etree.ElementTree, a leftover of the Python 2 to Python 3 migration, for paths of find() and similar methods, for the tag of iter(), and for the names of events of XMLPullParser and iterparse(). It now raises the same exceptions as the Python implementation.

  • gh-157242: io.BytesIO is no longer closed on write() and truncate() failure (MemoryError). Patch by Victor Stinner.

  • gh-157325: Fix an out-of-bounds read in the hz incremental decoder when the input ends with ~.

  • gh-157301: Corrige asyncio.Task travando o laço de eventos quando uma inicialização imediata (eager start) falha ao entrar no contexto da tarefa.

  • gh-156955: Speed up csv.writer() by caching the set of characters that need quoting or escaping in the dialect. Writing long fields is now up to 5 times faster.

  • gh-157213: Corrige o problema em que asyncio.gather() deixava arestas obsoletas no grafo de await em tarefas filhas que persistiam após a conclusão da função.

  • gh-157176: Make the time.struct_time type immutable to prevent reference cycles between the type and its instances. Patch by Shamil Abdulaev.

  • gh-156002: zipfile again reads members through a third-party decompressor installed by monkey-patching the private _get_decompressor() to return an object that only implements old BZ2Decompressor API from Python 3.3. Calling decompress() with one argument is deprecated. Note that decompressors without needs_input and two-argument decompress() are vulnerable to CVE 2026-15310.

  • gh-157159: A mensagem de uso exibida por python -m tabnanny quando nenhum argumento é fornecido agora sugere python -m em vez do arquivo-fonte.

  • gh-123018: Fix readline.write_history_file() and readline.append_history_file() producing a history file that readline.read_history_file() could not load when a limit was set with readline.set_history_length() and Python was built against libedit. This works around NetBSD PR 60322.

  • gh-157127: Reword the argparse error message reported for a missing required mutually exclusive group to one of the following arguments is required: --foo, --bar, so that the argument names are separated by commas.

  • gh-157146: linecache can now read the source of a module that was imported from a zip archive on sys.path when given only the file name, as pdb, warnings and doctest do.

  • gh-157058: asyncio.wait_for() com um tempo limite não positivo agora registra o waiter no grafo de chamadas.

  • gh-156933: Corrige valores de retorno inteiros incorretos de funções de retorno do ctypes em algumas plataformas, como s390x.

  • gh-157048: Preserve the position and contents of io.BytesIO when BytesIO.__init__() fails because a buffer is exported.

  • gh-157025: Fix transport cleanup when cancelling asyncio.loop.sendfile() while waiting for the write buffer to drain in the native implementation.

  • gh-156961: Fix tkinter.font.nametofont() and the tkinter.font.Font constructor for a font name or description returned by Tk as a Tcl object, for example by ttk.Style.lookup().

  • gh-156988: asyncio.print_call_graph() não mais trunca a pilha de chamadas no gerador síncrono.

  • gh-156970: Define a docstring de unittest.mock.Mock.return_value.

  • gh-156946: Fix a crash in curses.panel when the finalizer of a panel’s user pointer runs while the panel is being deallocated. The panel is now taken off the panel stack before its user pointer is dropped.

  • gh-156924: annotationlib.ForwardRef.evaluate() agora resolve proxies de importação preguiçosa (lazy import) encontrados no espaço de nomes. Com FORWARDREF, uma importação preguiçosa que falha ao ser resolvida agora resulta em um ForwardRef em vez do proxy de importação preguiçosa, e com VALUE, a exceção subjacente é propagada.

  • gh-156865: Don’t raise exceptions on overflows in ctypes.c_float_complex. Patch by Sergey B Kirpichev.

  • gh-156920: Fix asyncio on Windows: closing a DatagramTransport under ProactorEventLoop while datagrams were still queued, or while an in-flight write failed right as close() was draining the buffer, could strand the queued data and never call connection_lost(), hanging the close indefinitely.

  • gh-156864: array.array() setter now correctly detects overflows for the 'e', 'f' and 'Zf' type codes. Patch by Sergey B Kirpichev.

  • gh-156867: Raise OverflowError’s for native 'Zf' format in struct.pack(), like for 'f' format. Previously overflows in the float complex type were silent. Patch by Sergey B Kirpichev.

  • gh-156810: Fix a UnicodeEncodeError crash in the sampling profiler’s collapsed-stack export (--collapsed) when a sampled frame’s function or file name contains non-ASCII or surrogate-escaped characters. The output file is now written as UTF-8.

  • gh-124697: The symtable module now represents inlined list, set and dict comprehensions (PEP 709) as their own symbol table entries of type INLINED_COMPREHENSION.

  • gh-156797: Fix xml.sax.saxutils.XMLGenerator: the namespace URI is now escaped in the namespace declaration. Previously a URI containing &, < or a quote character produced a document which cannot be parsed.

  • gh-63102: XMLPullParser and iterparse() now support the target parameter. The reported object is the value returned by the corresponding method of the target, so no tree is built if the target does not build one. Only the standard TreeBuilder was supported in the C implementation before.

  • gh-61290: xml.etree.ElementTree no longer refuses to serialize attributes without a namespace when the default_namespace option is used. The default namespace declaration does not apply to attribute names, so an unqualified attribute name is written as is, and a qualified attribute name is always written with a prefix.

  • gh-83895: o xml.etree.ElementTree agora aceita entradas maiores que 2 GiB na implementação em C. Os dados são fornecidos ao Expat em blocos — como o xml.parsers.expat já fazia — em vez de levantar uma OverflowError.

  • gh-99064: Corrige xml.etree.ElementTree.parse() ao lidar com um arquivo de texto ou outra fonte de dados do tipo str na implementação em C. A codificação declarada no documento era aplicada ao texto já decodificado, resultando em mojibake; agora, ela é ignorada, assim como ocorre ao analisar com XMLParser.feed() ou fromstring().

  • gh-89499: ElementTree.write(), tostring() and tostringlist() now support the standalone parameter, the value of the standalone document declaration in the XML declaration.

  • gh-156713: Fix nturl2path.pathname2url() and nturl2path.url2pathname(): the filesystem encoding and error handler are now used for percent-encoding and decoding, as in urllib.request. Previously paths containing surrogate characters raised UnicodeEncodeError.

  • gh-156774: Speed up pdb startup by only importing asyncio when the program being debugged has already imported it.

  • gh-156439: socket.if_nametoindex() and socket.if_indextoname() are now available on platforms that provide them but not if_nameindex, such as Android before API level 24.

  • gh-156698: Fix asyncio.ProactorEventLoop UDP transports so that a write error no longer strands a paused protocol: the write loop is now rescheduled when data remains buffered, and the protocol is resumed when the buffer has drained.

  • gh-127057: Corrige transportes UDP de asyncio.ProactorEventLoop de forma que uma ConnectionResetError levantada por WSARecvFrom deixe de interromper o laço de leitura.

  • gh-156665: xml.dom.minidom now validates namespaces in createElementNS(), createAttributeNS() and setAttributeNS(), and when setting prefix of an attribute. NamespaceErr is now raised for a malformed qualified name, for a prefix with an empty namespace, and for illegal use of the xml and xmlns prefixes.

  • gh-156658: xml.dom and xml.etree.ElementTree no longer treat characters which are not white space in XML (such as U+00A0) as white space. Previously they could be lost in indent(), canonicalize() with strip_text=True, and when parsing with the whitespace-in-element-content feature turned off.

  • gh-81623: toprettyxml() in xml.dom.minidom and indent() in xml.etree.ElementTree no longer add whitespace inside an element which is marked with xml:space="preserve" or which contains text (toprettyxml() also takes into account the content model declared in the DTD). Previously such indentation changed the content of the element.

  • gh-54092: Implement writexml() for document fragments in xml.dom.minidom, so that toxml() and toprettyxml() now work for them. They write the children of the fragment, without adding a level of indentation.

  • gh-156512: Corrige asyncio perdendo uma conexão duas vezes quando resume_writing() fecha o transporte.

  • gh-44376: writexml() in xml.dom.minidom now writes the namespace declarations needed to serialize the namespaces of the element and its attributes, if they are not already declared for an ancestor. The document is not modified.

  • gh-156545: Fix the sampling profiler’s flamegraph export so that profiling a deeply recursive program no longer fails with RecursionError instead of producing a flamegraph. Patch by tonghuaroot.

  • gh-156523: Corrige asyncio.as_completed() não registrando a tarefa aguardada no grafo de chamadas.

  • gh-156476: The pure Python implementation of queue.SimpleQueue.get() now ignores timeout when block is false, matching the documented behavior and the C implementation. It previously raised ValueError.

  • gh-156444: Fix matching of a negated character set in a bytes pattern compiled with both re.IGNORECASE and re.LOCALE. The case closure is now applied to the members of the set, so that [^bc] no longer matches b'B'.

  • gh-156360: Add the PYTHON_TURTLE_LANG environment variable to select the language of turtle docstrings. Docstring dictionary entries naming a method which does not exist in the running version are no longer reported.

  • gh-156400: Fix socket and pipe leaks in asyncio when protocol_factory() raises in loop.create_datagram_endpoint, loop.connect_read_pipe, and loop.connect_write_pipe. The socket or pipe is now closed instead of leaking until garbage collection.

  • gh-156408: Corrige asyncio.print_call_graph() levantando AttributeError quando chamado em uma tarefa que já foi concluída.

  • gh-156404: Restaura a compatibilidade com arquivos .pth gerados antes do Python 3.15 no módulo site. Injeta a variável fullname no quadro que executa o código pth.

  • gh-156353: Corrige a análise do configparser ao usar espaço em branco em delimiters.

  • gh-156327: Fix asyncio.print_call_graph() including its own frame in the printed call stack.

  • gh-108549: Fix asyncio.Task, when the task has a pending cancellation, replace exc exception with a asyncio.CancelledError unless it is SystemExit or KeyboardInterrupt, which must propagate unchanged.

  • gh-156261: pwd.getpwuid() now raises OverflowError instead of KeyError if the user id is out of the range of the C uid_t type, as grp.getgrgid() does for the group id.

  • gh-156230: curses.window.instr(), in_wstr() and in_wchstr() no longer limit the count to 2047, which silently truncated a longer line.

  • gh-156228: The ssl and hashlib modules now route OpenSSL memory allocations through the Python raw memory allocators, making OpenSSL memory usage visible to tracemalloc and to custom allocators installed with PyMem_SetAllocator().

  • gh-156180: zlib.adler32_combine() e zlib.crc32_combine() agora levantam ValueError se o argumento len2 for negativo, em vez de retornarem valores inválidos ou travarem indefinidamente, respectivamente.

  • gh-156166: ssl: A failed assignment or deletion of the _msg_callback attribute of ssl.SSLContext no longer removes the current callback. Deleting it now raises AttributeError instead of TypeError.

  • gh-156173: Calling zlib.Decompress.flush() on invalid compressed data now raises zlib.error instead of being silently ignored.

  • gh-156124: Fix a crash in the free-threaded build when deleting the contents attribute of a ctypes pointer.

  • gh-156112: _ios_support não falha mais ao importar quando ctypes.util.find_library() não consegue resolver o ambiente de execução do ObjC através do cache compartilhado do dyld, como é o caso no iOS 13. O ambiente de execução agora é carregado pelo nome, o qual o dyld resolve diretamente contra o cache.

  • gh-156101: Fix sqlite3.Cursor.arraysize being set to 0 if the assigned value is too large. The attribute is now left unchanged if the assignment fails.

  • gh-156100: Fix crashes in sqlite3.Connection when deleting the autocommit attribute or setting it to an integer which does not fit in C long. Both now raise an exception.

  • gh-156099: Corrige uma falha ao excluir o atributo keylog_filename de ssl.SSLContext. Agora, isso levanta uma exceção AttributeError.

  • gh-156067: Fix error handling in the zoneinfo accelerator module when a transition index is -1 or a TZ string’s __bool__ raises.

  • gh-155997: Fix concurrent.interpreters.list_all(). It failed if an interpreter was destroyed during the call, in particular by a garbage collection which finalized the object owning the last reference to it.

  • gh-155974: Corrige uma regressão no Python 3.15: addstr(), addnstr(), insstr() e insnstr() voltam a restaurar os atributos da janela quando a escrita falha, em vez de deixar o attr temporário aplicado.

  • gh-155941: Fix asyncio.start_server() when a plain-function client_connected_cb raises: the error is now reported like the coroutine case and the transport is closed, instead of leaving the connection open forever (which also made asyncio.Server.wait_closed() hang).

  • gh-155934: Fix a socket leak in asyncio when transport creation fails for a connection accepted by a server, and report the error via the loop exception handler even when debug mode is disabled.

  • gh-155966: math.tanpi() now raises ValueError for half-integer values (e.g., tanpi(1.5)), as these are poles of the function.

  • gh-155952: Corrige as assinaturas de sqlite3.Connection.execute(), warnings.warn() e locale.setlocale() que renderizavam <unrepresentable> em vez dos padrões corretos para os parâmetros.

  • gh-155596: Correção para pprint.pprint() e pprint.pformat() com expand=True, que não respeitavam o parâmetro width para valores aninhados. A largura do prefixo 'key': não era contabilizada ao determinar se um valor cabia na linha atual; assim, valores associados a chaves longas podiam exceder o limite de width em vez de serem expandidos.

  • gh-155888: Corrige asyncio.WriteTransport.writelines() travando o transporte quando o último pedaço de dados estiver vazio.

  • gh-155869: Corrige reorganize() em dbm.dumb falhando ao persistir deslocamentos de valores atualizados, o que podia causar perda de dados após reabrir o banco de dados.

  • gh-121291: enum.Flag (and enum.IntFlag) subclasses no longer have a mixin base’s own __or__, __and__, __xor__, __ror__, __rand__, __rxor__, or __invert__ override silently replaced by Flag’s default implementation.

  • gh-155863: Add the WACS_* constants to the curses module. They are the counterparts of the ACS_* line-drawing codes as curses.complexchar cells, and are added, like the latter, by curses.initscr() and curses.newterm().

  • gh-155843: hmac: ensure that HMAC objects are properly initialized to prevent rare crashes on allocation failures. Patch by Bénédikt Tran.

  • gh-155835: hashlib: Fix a data race when accessing digest_size on BLAKE-2 objects. Patch by Bénédikt Tran.

  • gh-155835: hashlib: Fix data races when accessing digest_size and block_size on SHA-3 objects. Patch by Bénédikt Tran.

  • gh-155811: Add a sequence counter to GC statistics to prevent _remote_debugging returning inconsistent snapshots caused by non-atomic reads. Patch by Maurycy Pawłowski-Wieroński.

  • gh-155717: multiprocessing’s default start method is now “spawn” instead of "forkserver" when there is no writable temporary directory, such as on a read-only file system. Previously starting a process failed with an OSError there. Patch by Bénédikt Tran.

  • gh-155775: Fix a regression in imaplib introduced in the fix for gh-63121: refreshing the capabilities after a successful login() or authenticate() consumed the CAPABILITY response, so it could no longer be read with response().

  • gh-113318: Corrige falhas ao excluir um atributo cujo método setter é gerado pela Clínica de Argumentos e não está preparado para a exclusão, incluindo frame.f_trace_opcodes e os atributos context, owner e session de _ssl._SSLSocket. A exclusão de tal atributo agora levanta uma AttributeError.

  • gh-155781: Corrige um possível travamento em construções com threads livres quando o registro de conversores do sqlite3 for modificado concorrentemente enquanto um cursor constrói seu mapa de conversão de linhas.

  • gh-83371: Fix a deadlock in multiprocessing.pool.Pool when callback or error_callback raises an exception. It killed the thread which handles results, so that the pool hung forever. The exception is now the result of the job, as an error raised while iterating the input, and is raised by AsyncResult.get().

  • gh-155702: Corrige atribuição de fatia em sqlite3.Blob com passo (step). Ele alterava o objeto de bytes lido do blob, que para um único byte é um singleton imortal, de modo que o valor daquele byte era alterado em todo o processo.

  • gh-90756: xml.etree.ElementTree.ElementTree.write() now treats the utf-8-sig encoding as utf-8 in the XML declaration.

  • gh-44871: Parser objects of the XML parser have a new method GetSpecifiedAttributeCount(). It tells how many of the attributes reported to StartElementHandler were given in the start tag rather than defaulted from the DTD.

  • gh-44871: xml.dom.minidom now conforms closer to the DOM Level 1 specification. The factory methods now raise InvalidCharacterErr if the name is not a valid XML name. Removing an absent attribute with Element.removeAttribute() or Element.removeAttributeNS() no longer raises NotFoundErr, it has no effect as the DOM specifies. Inserting or setting a node created by another document now raises WrongDocumentErr, setting an attribute node which belongs to another element now raises InuseAttributeErr, and inserting a node into itself or its descendant now raises HierarchyRequestErr. A document can no longer have two element or two document type children, and a document fragment can no longer have notation children. Attributes defaulted in the DTD are no longer omitted when parsing, and Attr.specified now reports whether the attribute was given in the start tag. EntityReference nodes and Document.createEntityReference() are now implemented.

  • gh-80762: Fix dir() on unittest.mock.Mock objects created with a tuple spec: it raised TypeError. Such spec is now also documented.

  • gh-61366: http.cookiejar.MozillaCookieJar.save() now writes 0 in the expiration time field for session cookies, as curl and Wget do. Previously this field was left empty, and such lines were ignored by curl and Wget.

  • gh-153400: On Linux, os.copy_file_range() and os.memfd_create() now fall back to the raw syscall when the libc Python is built against does not provide the wrapper function, so they stay available on interpreters built against a libc older than glibc 2.27.

  • gh-153400: os and signal: Use glibc functions instead of syscall(): pidfd_open(), pidfd_getfd() and pidfd_send_signal() (glibc 2.36), gettid() and getdents64() (glibc 2.30), and getrandom() (glibc 2.25). Patch by Victor Stinner.

  • gh-155496: The ctypes.set_errno and ctypes.set_last_error auditing events are now raised after the argument is converted to an integer, therefore they are no longer raised if the argument is invalid.

  • gh-155496: io.RawIOBase.readinto() and io.RawIOBase.write() now raise TypeError instead of NotImplementedError if they are called without the required argument.

  • gh-155468: Corrige netrc para distinguir tokens entre aspas vazios do fim do arquivo, para que arquivos malformados não façam mais com que o conteúdo restante seja silenciosamente ignorado.

  • gh-155519: Evita uma condição de corrida de dados em construções com threads livres ao ler e escrever variáveis de contexto a partir de threads diferentes.

  • gh-155336: Fix error handling in socket.gethostbyaddr() and socket.gethostbyname_ex() when hostname resolution fails.

  • gh-118318: Remove the write_c14n() method of xml.etree.ElementTree.ElementTree and the support of method="c14n" in write() and tostring(). They never worked and always raised ValueError. Use xml.etree.ElementTree.canonicalize() instead.

  • gh-155433: Corrige a perda de cancelamento externo por asyncio.TaskGroup após cancel().

  • gh-155418: Corrige o travamento de asyncio.TaskGroup quando uma tarefa criada por asyncio.eager_task_factory() cancela o grupo antes de ser suspendido.

  • gh-102475: Fix os.path.realpath() on Windows: the unresolved part of the path is now appended, not joined, so a file name which looks like a drive (e.g. spam:eggs) no longer discards the resolved part. A path relative to another drive is now resolved against the root directory of that drive.

  • gh-89760: Corrige os.path.realpath() no Windows: o prefixo \\?\ não é mais removido de caminhos com GUID de volume, o que tornava o resultado inválido.

  • gh-84419: Corrige os.stat() no Windows: pontos e espaços ao final do nome, que são ignorados pelo sistema operacional, não são mais levados em consideração ao inferir as permissões de execução a partir da extensão do arquivo.

  • gh-111331: Closing a io.BytesIO object which has exported buffers no longer fails with BufferError. The exported buffers keep the data alive and stay usable. As a result, destroying or garbage collecting such object no longer emits an unraisable exception.

  • gh-108885: Doctests run by the unittest test runner now report every example, as in verbose mode, if the runner reports more than the test names, i.e. its verbosity is 3 or higher. The -v option of unittest can now be repeated, so python -m unittest -vv asks for this. Added also the verbosity attribute of unittest.TestResult.

  • gh-155319: warnings.warn_explicit() now displays the source line taken from the loader of the module whose globals are passed as module_globals. It also no longer raises IndexError if lineno is out of the range of the module source.

  • gh-123011: warnings.warn_explicit() no longer emits a spurious DeprecationWarning or raises ImportError when it is called with the globals of the __main__ module.

  • gh-69370: python -m inspect --details no longer fails with UnicodeEncodeError if the path of the module contains characters unencodable in the encoding of sys.stdout. Such characters are now escaped with backslashes.

  • gh-69371: Fix pydoc for modules whose path contains undecodable bytes. pydoc.writedoc() and the pydoc HTTP server no longer fail with UnicodeEncodeError: the file URL is now percent-encoded using the filesystem encoding, and characters unencodable in the generated HTML page are escaped with backslashes.

  • gh-155236: Add the dedent parameter in inspect.cleandoc() and inspect.getdoc(). pydoc no longer dedents documentation strings, so the indentation of the parameter descriptions generated by Argument Clinic is preserved.

  • gh-155009: Corrige argparse.ArgumentParser para preservar o nome do programa a partir de sys.argv[0] quando um módulo nomeado for executado como o programa principal sem substituir sys.argv[0].

  • gh-150942: Improve the performance of readlines() for io.BytesIO.

  • gh-155063: Atualiza a versão do pip empacotado no ensurepip para a versão 26.2.1

  • gh-153711: No macOS, adiciona verificações em tempo de execução ao redor das chamadas de sistema pipe2 (2) e dup3 (2), além das verificações existentes em tempo de construção. Isso significa que o Python construído no macOS 27 (onde essas chamadas estão disponíveis) pode ser executado no macOS 26 (onde não estão).

  • gh-155143: Corrige o vazamento da tarefa chamadora em asyncio.shield() — via grafo de await e funções de retorno — quando a função é chamada em um future que nunca é resolvido.

  • gh-75008: csv.Sniffer.sniff() now detects the lineterminator parameter by a majority vote among the line endings of the sample.

  • gh-155051: decimal.localcontext() now raises TypeError if a keyword argument is None, as the pure Python implementation already did. Previously the C implementation silently ignored it.

  • gh-99772: Fix comparisons and hashing of datetime.time objects with sub-minute UTC offsets.

  • gh-155044: optparse.Values objects now support copy.replace().

  • gh-155043: argparse.Namespace objects now support copy.replace().

  • gh-155041: decimal.Context objects now support copy.replace().

  • gh-155040: tarfile.TarInfo objects now support copy.replace().

  • gh-155063: Atualiza a versão do pip empacotado no ensurepip para a versão 26.2

  • gh-155033: CSV dialects (instances of csv.Dialect subclasses and dialect objects returned by csv.get_dialect()) now support copy.replace().

  • gh-154936: Corrige o decodificador json em Python puro para relatar a posição correta para caracteres de controle literais inválidos em strings JSON.

  • gh-154904: Speed up shutil import by probing the _bz2, _lzma and _zstd extension modules instead of importing the bz2, lzma and compression.zstd wrappers, which are now only imported when an archive is actually created or extracted.

  • gh-154892: Corrige um erro no acelerador C para zoneinfo onde subclasses de datetime.datetime retornando -1 para hour, minute ou second podiam incorretamente levantar um SystemError.

  • gh-154871: Corrigido um travamento em asyncio.Task.get_context() quando chamado em uma tarefa não inicializada.

  • gh-154848: O acelerador C do pickle agora impõe limites de quadro ao desserializar com pickle, assim como a implementação em Python puro já fazia. Um argumento que se estende além do limite de um quadro, ou um quadro que começa antes do anterior ter terminado, agora levanta pickle.UnpicklingError em vez de ser lido silenciosamente através do limite. Isso evita que os dados carregados divirjam da desmontagem do pickletools do mesmo pickle.

  • gh-154885: os.get_terminal_size() agora verifica isatty antes de chamar ioctl, o que reduz o ruído de log no Android.

  • gh-154855: Fix curses.window.instr(), in_wstr() and in_wchstr() returning one character too few when the curses module is built against a curses library that counts the terminator in the requested length, such as the NetBSD one.

  • gh-154874: Fix curses.termattrs() returning a negative value on a terminal that supports curses.A_ITALIC, which left its result unusable as an attribute mask.

  • gh-151728: Clear the internal typing caches from an exit handler. Previously, an extension module that leaked a reference to typing would also keep every subscripted type alive past interpreter shutdown, including types owned by unrelated extension modules.

  • gh-154791: Fix asyncio.Future (C implementation) losing the initial exception traceback frames when Future.result() is called more than once. Previously, the C implementation cleared the stored traceback after the first call, causing subsequent raises to omit the original raise site. The pure-Python implementation was unaffected.

  • gh-94984: Add the mode parameter to asyncio.loop.create_unix_server() and asyncio.start_unix_server() to set the permissions of the Unix socket file created for path, applied before the server starts accepting connections.

  • gh-154744: Improve detection of skipinitialspace in csv.Sniffer.sniff().

  • gh-154726: Fix shutil.copyfile() to copy a symbolic link to a special file when follow_symlinks=False instead of raising SpecialFileError.

  • gh-154738: Corrige ExternalEntityParserCreate() não propagando a configuração de adiamento de reanálise para o subanalisador, o que deixava GetReparseDeferralEnabled() retornando um valor não inicializado. Patch por tonghuaroot.

  • gh-93251: Corrige UnicodeDecodeError em funções do socket (como getaddrinfo() e gethostbyaddr()) quando a mensagem de erro localizadas da biblioteca C não é UTF-8: decodifica-a a partir da codificação da localidade (locale).

  • gh-148468: Corrige uma regressão no argparse onde a ajuda de argumento colorida contendo especificadores de formato não aceitava objetos proxy semelhantes a strings.

  • gh-154638: Improve import time of argparse by lazily importing several dependencies.

  • gh-142035: Corrige a quebra de linha incorreta do texto de ajuda do argparse quando a cor está ativada.

  • gh-135736: Corrige asyncio.TaskGroup para não envolver um GeneratorExit em um BaseExceptionGroup se ele foi levantado pelo corpo do grupo de tarefas e nenhuma das tarefas no grupo levantou exceções.

  • gh-154594: Fix copy.deepcopy() so that an object whose deep copy is None is still memoized. Patch by tonghuaroot.

  • gh-154568: Corrige a desserialização com pickle no array de float16 em little-endian.

  • gh-154566: Corrige array.array.byteswap() corrompendo dados para arrays 'Zd' (complex double) com mais de um elemento: o laço de item de 16 bytes avançava o ponteiro do buffer em apenas 8 bytes por iteração, fazendo com que os itens após o primeiro fossem embaralhados.

  • gh-154551: Corrige ctypes.util.find_library() retornando None em localidades não-UTF-8.

  • gh-154523: Fixed data-race when calling io.TextIOBase.detach() in free-threaded build.

  • gh-135683: logging.FileHandler and logging.handlers.WatchedFileHandler now honor logging.raiseExceptions for errors that occur while opening the file, like for other errors during logging.

  • gh-154199: Make ctypes.util.find_msvcrt() always return None for compatibility reasons.

  • gh-135736: Fix asyncio.TaskGroup silently discarding errors from sibling tasks whenever the async with block exits with a SystemExit or KeyboardInterrupt. These errors are now reported via loop.call_exception_handler() instead of being lost.

  • gh-79366: Corrigida uma condição de corrida no logging: se um manipulador era removido enquanto um registro estava sendo emitido, os manipuladores seguintes do mesmo logger podiam ser ignorados.

  • gh-82535: logging.handlers.SysLogHandler no longer fails if the address cannot be resolved when the handler is created. The address is resolved again when a record is emitted.

  • gh-70990: logging.handlers.SysLogHandler now accepts a bytes address of a Unix domain socket, including an address in the abstract namespace. Previously only str was recognized, and a bytes address raised ValueError.

  • gh-154189: Corrigido um potencial uso-após-liberação ao chamar functools.partial(). Agora, ao invocar um objeto partial(), a função armazenada, argumentos posicionais e argumentos nomeados são preservados durante a chamada em caso de reentrada.

  • gh-154470: Corrigido um ^J espúrio impresso ao final de cada linha de código-fonte pelo comando list do pdb quando a saída está colorida (por exemplo, ao anexar a um processo em execução). A linha de código-fonte agora é limpa antes de ser colorida, assim como o comando where já fazia.

  • gh-73458: Corrige logging.config.listen(): deixava o chamador esperando pelo evento ready para sempre se o servidor não pudesse ser iniciado, por exemplo, se a porta fosse inválida ou já estivesse em uso. Agora também se vincula a um endereço IPv6 se o host não tiver endereço IPv4, por exemplo, se localhost for apenas um alias para ::1.

  • gh-154460: Corrige time.strftime() e datetime.datetime.strftime() retornando um número de semana ISO 8601 errado (%V) no OpenBSD.

  • gh-154467: Corrigido o anexo remoto do pdb (python -m pdb -p PID) enviando um prompt vazio para o cliente em vez de (Pdb) quando o processo alvo possui um terminal interativo.

  • gh-153970: Calling str() on a subprocess.CalledProcessError no longer raises TypeError when its returncode is not an integer, such as None.

  • gh-154435: Corrige os.posix_fadvise() e os.posix_fallocate() no DragonFly BSD: levantavam OSError com um código de erro sem sentido, porque essas funções retornam -1 e definem errno lá.

  • gh-154399: Corrige a ativação do venv em um csh não interativo: activate.csh não falha mais quando a variável prompt não está definida.

  • gh-154389: Corrige uuid.uuid1() no OpenBSD: retornava um UUID versão 4, porque uuid_create() gera UUIDs aleatórios nesta plataforma.

  • gh-154335: O perfilador profiling.sampling agora respeita NO_COLOR, FORCE_COLOR e PYTHON_COLORS, e evita saídas coloridas quando não está escrevendo em um terminal.

  • gh-154324: Corrige os.sendfile() no illumos: não relata mais uma transferência bem-sucedida quando a chamada de sistema subjacente falhou sem escrever nenhum dado.

  • gh-154307: Corrige tempfile.TemporaryDirectory.cleanup() no DragonFly BSD, onde a remoção de um arquivo com o sinalizador UF_NOUNLINK falhava com EISDIR em vez de EPERM.

  • gh-154291: Corrige socket.has_dualstack_ipv6() para retornar False em plataformas como DragonFly BSD, onde definir IPV6_V6ONLY para 0 silenciosamente não tem efeito.

  • gh-154283: No DragonFly BSD, threading.get_native_id() agora retorna um valor que é único entre processos, correspondendo a outras plataformas.

  • gh-154258: Corrige uma falha em mmap.mmap.resize() no NetBSD ao aumentar um mapeamento anônimo compartilhado. O resize() agora levanta ValueError neste caso, como já fazia no Linux.

  • gh-131565: ctypes.util.dllist() agora funciona no NetBSD. Ele é implementado no módulo de extensão _ctypes para que dl_iterate_phdr() reporte todas as bibliotecas compartilhadas carregadas: no NetBSD ele reporta apenas o grupo de mapa de links do objeto chamador, o que os excluía quando chamado via ctypes.

  • gh-154225: Corrige os.openpty() no Solaris e illumos: não deixa mais o pseudoterminal como o terminal de controle do processo chamador.

  • gh-154227: Corrige os.posix_openpt() no OpenBSD, onde rejeitava o sinalizador O_CLOEXEC.

  • gh-139373: Fix asyncio.subprocess.Process.communicate() losing already-read output when it is cancelled; the output is now retained and returned by a subsequent communicate() call. Patch by Kumar Aditya.

  • gh-145030: Corrige transportes de encadeamento (pipe) de escrita do asyncio para FIFOs nomeados no macOS e Solaris. Dados não lidos no FIFO faziam o transporte reinterpretar um evento de poll como desconexão do leitor, fechando incorretamente o transporte.

  • gh-154194: Fix the sampling profiler dropping entire samples when a non-fatal read fails; frames now keep any readable metadata, and long funcnames and filenames are truncated instead. Patch by Maurycy Pawłowski-Wieroński.

  • gh-154176: Corrige uma falha em locale.strxfrm() no DragonFly BSD, cujo wcsxfrm() não oferece suporte a tamanho zero.

  • gh-154836: Corrige subprocess.Popen.wait() levantando TypeError (macOS e outros BSDs) ou OverflowError (Linux) para valores muito grandes de timeout como float('inf'), uma regressão do 3.15 no novo wait orientado a eventos. Também corrige select.kqueue.control() mascarando OverflowError para timeouts fora do intervalo como TypeError.

  • gh-154146: Fix accuracy of math.acospi() for arguments close to 1 on platforms that do not provide acospi() in libm.

  • gh-153005: concurrent.interpreters.Queue.get() and concurrent.interpreters.Queue.put() now compute their timeout deadline from time.monotonic() instead of the wall clock, so adjusting the system clock during the call no longer makes them over- or under-wait.

  • gh-153772: Verificações isinstance() em relação a classes do collections.abc tais como Mapping não levantam mais AttributeError quando a instância não possui __class__. O mecanismo de classe base abstrata agora recorre ao tipo do objeto nesse caso, correspondendo ao comportamento do isinstance() embutido.

  • gh-154090: Registra o modo de perfilamento nos perfis binários do Tachyon e rejeite comparações diferenciais cujos modos conhecidos não correspondem.

  • gh-154086: Armazena contagens de amostras por thread nos flamegraphs Tachyon para que a filtragem de uma thread atualize as larguras e totais dos quadros.

  • gh-154060: Armazena a duração medida e a taxa de amostragem em perfis binários do Tachyon para que permaneçam disponíveis em flamegraphs reproduzidos.

  • gh-154085: Evita que flamegraphs diferenciais dupliquem o tempo próprio (self time) entre nós de linha para a mesma função.

  • gh-154088: Faz com que o Tachyon conte e renderize pilhas omitidas de forma consistente em flamegraphs diferenciais.

  • gh-154089: Não exibe estatísticas de eficiência de amostragem indisponíveis em flamegraphs do Tachyon reproduzidos.

  • gh-154062: Stop normalizing differential flamegraph baselines to the duration of the current profile.

  • gh-154053: Corrige a compilação do módulo ssl contra o LibreSSL, que não fornece SSL_CTX_set1_sigalgs_list() e SSL_CTX_set1_client_sigalgs_list(). Os métodos set_server_sigalgs() e set_client_sigalgs() de ssl.SSLContext agora levantam NotImplementedError no LibreSSL.

  • gh-154002: The pure-Python pickle unpickler no longer replaces a TypeError raised by an old-style instance constructor with a new one carrying the traceback object in its args. The original error now propagates, as it already did in the C implementation.

  • gh-154001: Corrige random.binomialvariate() levantando ZeroDivisionError quando random.random() retorna zero.

  • gh-118150: Expose automated junk heuristic kwarg-only flag autojunk from difflib.SequenceMatcher to the public functions and class methods in the difflib. See difflib.SequenceMatcher documentation for details and issue gh-118150 for the motivation.

  • gh-153967: argparse.ArgumentParser.print_usage() and argparse.ArgumentParser.print_help() won’t silently fail when an invalid file object is specified. Patch by Timothy Poon.

  • gh-153906: Modernize the HTML output of pydoc: use semantic HTML5 markup and a new style sheet based on the python-docs-theme used by docs.python.org, with dark mode support. Class members inherited from other classes are now collapsed by default.

  • gh-153908: Corrige corrida de dados ao chamar repr() em itertools.count sob a construção com threads livres.

  • gh-153896: Desduplica argumentos não-hasheáveis em typing.Literal.

  • gh-153903: Add ctypes.util.wrap_dll_function() for creating _CFuncPtr objects from a function signature.

  • gh-81241: Fix OSError when importing ctypes from a statically linked interpreter.

  • gh-153864: Em uma construção de curses larga (wide), curses.window.insch() agora insere um byte não-ASCII como o caractere que ele codifica na codificação da janela, consistentemente com addch(), em vez de seu ponto de código.

  • gh-153862: Em uma construção de curses larga, curses.window.inch() agora retorna o byte codificado da localidade de um caractere não-ASCII, correspondendo a instr(), em vez do byte baixo de seu ponto de código.

  • gh-153856: Add os.RWF_NOSIGNAL constant for Linux 6.18+.

  • gh-153844: symtable.symtable() now accepts an AST object, like the builtin compile().

  • gh-153838: Skip non-regular files in the profiling.sampling heatmap exporter instead of reading them unconditionally. Patch by tonghuaroot.

  • gh-146011: Corrige um uso-após-liberação na heap na implementação C do decimal ao chamar repr() após excluir o Context.

  • gh-141276: Fix duplicate SyntaxWarning messages when importing source modules from ZIP archives. zipimport.zipimporter.get_filename(), and therefore find_spec(), no longer compile source modules. A SyntaxError in a zipped source module is now raised when the module is executed rather than when it is found, matching the behavior of filesystem-based loaders.

  • gh-104533: Add ctypes.util.struct() and ctypes.util.CFieldInfo for generating structure types using annotations.

  • gh-153761: Corrige o cancelamento de asyncio.loop.sock_accept() descartando uma conexão pendente.

  • gh-153695: Aplica hash a um sqlite3.Row que contém um valor não-hasheável agora levanta TypeError em vez de SystemError. Patch por tonghuaroot.

  • gh-127049: Corrige uma condição de corrida no asyncio no Unix onde asyncio.subprocess.Process.send_signal(), terminate() ou kill() podiam sinalizar um processo não relacionado que foi reciclado no PID do filho já recolhido quando ThreadedChildWatcher é usado. Patch por Kumar Aditya.

  • gh-83273: csv.Sniffer.sniff() now deduces the dialect by trial parsing with the actual CSV parser instead of heuristics based on matching isolated fragments and on character frequencies. It can now detect the escapechar parameter, accepts non-ASCII delimiters in the delimiters argument, no longer misdetects the delimiter when the sample contains delimiter characters inside quoted fields, handles samples truncated at an arbitrary point, and no longer takes quadratic time on quoted samples. A sample consisting of a single column of quoted fields now raises csv.Error instead of guessing a delimiter from the content of the fields.

  • gh-153658: Corrige sqlite3.Connection.iterdump() levantando sqlite3.OperationalError quando o nome de uma tabela contém uma aspa simples. Patch por tonghuaroot.

  • gh-98078: Fix asyncio SSL transports not sending the fatal TLS alert to the peer when the TLS handshake fails or when receiving corrupted data, and not sending the close_notify alert to the peer when the TLS shutdown fails. The peer can now tell why the connection was dropped (for example, certificate verification failure or no TLS version in common) instead of seeing the connection abruptly closed.

  • gh-85943: Corrige funções do struct levantando BytesWarning sob a opção de linha de comando -bb quando um formato str é usado após um formato bytes igual (ou vice-versa). O cache de formato interno não mistura mais chaves de str e bytes.

  • gh-153603: Fix a crash in the ISO-2022 decoders when decoding a byte after an unknown charset designation is set via the decoder’s setstate method. Patch by tonghuaroot.

  • gh-153539: Corrige uma falha na implementação do C de io.TextIOWrapper.tell() quando o método getstate do decodificador aciona uma busca reentrante, ou quando outro thread busca o mesmo fluxo simultaneamente. Patch por tonghuaroot.

  • gh-153502: imaplib.IMAP4.copy(), move(), fetch(), store(), search(), sort(), thread() and expunge() now accept a keyword-only uid argument that selects the corresponding UID command, as a more convenient alternative to uid().

  • gh-153494: imaplib.IMAP4.search(), sort() and thread() (and the corresponding uid commands) now encode str search criteria to the declared charset, so international search text can be passed as ordinary str. When charset is None (as it must be under UTF8=ACCEPT), the criteria are sent using the connection encoding instead. A criterion passed as bytes is sent unchanged, for use with a charset that Python has no codec for.

  • gh-153513: Values of several Tcl object types returned by tkinter are now converted to the corresponding Python type instead of being wrapped in a _tkinter.Tcl_Obj: index, window, nsName and parsedVarName objects to str, and pixel screen distances with no unit suffix to int or float.

  • gh-153404: urllib.robotparser.RobotFileParser agora ignora silenciosamente um valor de Crawl-delay ou Request-rate escrito com dígitos não-decimais (como U+00B2 SUPERSCRIPT TWO) em vez de levantar ValueError e abortar a análise de todo o arquivo robots.txt.

  • gh-151292: Armazena a contagem de amostras no formato binário de profiling.sampling como um inteiro de 64 bits, ampliando o inteiro de 32 bits usado anteriormente. Isso quebra as gravações existentes. Sessões de perfilamento longas ou com muitas threads não falharão mais por causa de OverflowError. Patch por Maurycy Pawłowski-Wieroński.

  • gh-152754: Fix a crash when the same os.scandir() iterator is used concurrently from multiple threads. It no longer releases the directory handle while another thread is reading from it. Sharing an iterator between threads remains subject to race conditions: which entries each thread receives is unspecified.

  • gh-153417: Mensagens de erro de imaplib.IMAP4.select() e imaplib.IMAP4.uid() não levantam mais BytesWarning sob -bb quando o argumento de caixa de correio ou comando é bytes.

  • gh-153422: winfo_exists(), winfo_ismapped() and winfo_viewable() methods of tkinter widgets and edit_modified() of tkinter.Text now return a bool instead of an integer or, depending on wantobjects, a string.

  • gh-49555: imaplib now encodes non-ASCII mailbox names as modified UTF-7 (RFC 3501, section 5.1.3) in the default mode, so international mailbox names can be passed as ordinary str; under UTF8=ACCEPT they are sent as UTF-8 instead. A name that is not valid modified UTF-7, such as one with a bare &, is now encoded correctly instead of being sent as is. A str that is already valid modified UTF-7, or a bytes object, is sent unchanged.

  • gh-153395: curses.ascii predicates and the ctrl() and unctrl() functions now accept a curses.complexchar. ctrl() now returns a non-ASCII argument unchanged instead of masking it to a control character.

  • gh-153290: Fix a data race on the free-threaded build when io.BytesIO.__setstate__() installs the instance dictionary while another thread concurrently calls a method on the same object.

  • gh-153406: email.utils.parsedate_to_datetime() agora levanta ValueError em vez de OverflowError quando o ano analisado ou deslocamento de fuso horário está fora do intervalo, correspondendo ao seu comportamento documentado.

  • gh-152907: Restaura os sinalizadores de saída do terminal em modo “cooked” ao redor das funções de chamada de PyOS_InputHook no novo REPL (_pyrepl), de modo que a saída escrita por um gancho de entrada (por exemplo, um laço de eventos de um toolkit de GUI) não seja mais emitida com OPOST desabilitado e preserve seus caracteres de retorno de carro (carriage returns).

  • gh-153364: Make frame, coroutine and task-waiter walks iterative and bounded, avoiding potential hangs and stack overflows. Fix asyncio task inspection when awaited-by sets contain removed entries. Patch by Maurycy Pawłowski-Wieroński.

  • gh-153333: O método readprofile de tkinter.Tk agora lê os scripts de perfil do usuário usando a codificação declarada no arquivo, em vez da codificação da localidade.

  • gh-153319: The turtledemo viewer now reads each demo script as UTF-8 instead of the locale encoding.

  • gh-153296: Fix a data race and use-after-free when iterating over an io.StringIO object while it is being concurrently mutated. The __next__ method now properly acquires the object’s lock.

  • gh-152936: os.chroot(), os.initgroups(), os.setegid(), os.seteuid(), os.setgid(), os.setregid(), os.setresgid(), os.setresuid(), os.setreuid(), os.setuid(), and socket.sethostname() are now available on Android. Calling them without sufficient privileges now raises PermissionError instead of the functions being unavailable.

  • gh-153083: Adia o rastreamento pelo GC de um array.array para o final de sua construção. Patch por Donghee Na.

  • gh-153292: Corrige corrida de dados no repr de threading.RLock na construção com threads livres.

  • gh-153291: Corrige uma corrida de dados em readline.get_completer() e readline.get_pre_input_hook() na construção com threads livres: os getters liam o gancho armazenado sem a seção crítica que os setters correspondentes mantêm.

  • gh-153293: Corrige a TUI do perfilador de amostragem ao vivo mantendo estatísticas agregadas de opcodes obsoletas após uma redefinição de estatísticas.

  • gh-143990: Um tkinter.font.Font criado a partir de uma fonte nomeada, inclusive por copy(), agora copia suas opções configuradas em vez das opções resolvidas pelo font actual do Tcl, preservando um tamanho especificado em pixels (um tamanho negativo).

  • gh-148286: Corrige comportamento indefinido em compression.zstd.ZstdDecompressor.unused_data quando um quadro completo foi descompactado em uma única chamada.

  • gh-153210: Corrige falha na importação de array sob pressão de memória.

  • gh-153521: Add support for structured arguments in imaplib command methods. A message_set and lists of flags or other atoms can now be passed as sequences instead of preformatted strings, and the search(), fetch(), sort(), thread() and uid() methods accept a params keyword argument that substitutes and quotes ? placeholders.

  • gh-153256: Added the tk_print() method to tkinter.Canvas and tkinter.Text which prints the contents of the widget using the native print dialog. It requires Tk 8.7/9.0 or newer.

  • gh-153259: Added the tkinter.systray module which provides the SysTrayIcon class as an interface to the system tray icon and the notify() function which sends a desktop notification. They require Tk 8.7/9.0 or newer.

  • gh-72880: Added the tkinter.fontchooser module which provides the FontChooser class as an interface to the native font selection dialog.

  • gh-153200: Corrige math.isqrt() retornando um resultado incorreto para argumentos não menores que 2**64 que são instâncias de uma subclasse de int com um operador de comparação substituído.

  • gh-153158: Remove o argumento errôneo width de calendar.HTMLCalendar.formatmonthpage(), o qual podia descartar o ano do cabeçalho.

  • gh-66788: Add the utf-7-imap codec, implementing the modified UTF-7 encoding used for international IMAP4 mailbox names (RFC 3501, section 5.1.3).

  • gh-89869: Add imaplib.IMAP4.login_plain(), which authenticates using the PLAIN SASL mechanism (RFC 4616). Unlike login(), it supports non-ASCII user names and passwords.

  • gh-98092: Add imaplib.IMAP4.id(), a wrapper for the IMAP ID command (RFC 2971).

  • gh-153133: Corrige um vazamento de socket em asyncio.loop.create_connection() quando o transporte não pode ser criado.

  • gh-153068: Corrige cProfile.Profile.enable() para não mais sobrescrever erros do sys.monitoring.

  • gh-153062: Corrige uma falha ao iterar concorrentemente um iterador itertools.tee() na construção com threads livres.

  • gh-153056: Corrige string.Template levantando um ValueError espúrio quando o atributo pattern é um objeto de expressão regular compilado, o que a documentação permite. Na construção com threads livres, isso também ocorria como uma corrida de dados no primeiro uso concorrente.

  • gh-59396: tkinter.scrolledtext.ScrolledText gained a use_ttk parameter to use the themed tkinter.ttk frame and scroll bar instead of the classic tkinter widgets.

  • gh-143921: Restringe a verificação de caracteres de controle nos comandos do imaplib: apenas NUL, CR e LF são rejeitados agora. Outros caracteres de controle são válidos em strings entre aspas e podem ocorrer em nomes de caixas de correio retornados pelo servidor, portanto, agora são aceitos e enviados entre aspas.

  • gh-153037: Corrige ZstdFile levantando AttributeError em vez de io.UnsupportedOperation ao iterar sobre um arquivo que não está aberto para leitura.

  • gh-135661: Corrige html.parser.HTMLParser: um comentário vazio fechado abruptamente (<!--> ou <!--->) não se estende mais até um --> posterior na mesma chamada feed().

  • gh-153009: Fix compilation of curses on platforms that define the stdscr macro. Patch by Bénédikt Tran.

  • gh-152851: Evita uma falha quando a alocação falha ao copiar um objeto BLAKE-2s/2b. Patch por Bénédikt Tran.

  • gh-127636: Fix tarfile.TarFile.extract() to accept archive member names with a trailing forward slash, including those returned by tarfile.TarFile.getnames(). Contributed by Xiao Yuan.

  • gh-54930: Respostas de erro de http.server.BaseHTTPRequestHandler para linhas de requisição malformadas agora incluem uma linha de status e cabeçalhos em vez de serem enviadas no estilo HTTP/0.9 puro. Apenas uma requisição HTTP/0.9 válida (uma linha de requisição GET de duas palavras) agora recebe uma resposta no estilo HTTP/0.9.

  • gh-152997: On platforms providing the C library’s iconv(3) function, the codecs module now exposes every encoding known to iconv for which Python has no built-in codec. Such an encoding can be used by its name (for example "cp1133") or, to force the iconv-based engine even when a built-in codec exists, with an "iconv:" prefix (for example "iconv:latin1").

  • gh-119592: Corrige concurrent.futures.ProcessPoolExecutor abandonando o trabalho enviado para sempre quando um processo trabalhador saía ao atingir seu limite max_tasks_per_child após shutdown() ser chamado com wait=False: um trabalhador de substituição é agora gerado e o trabalho restante executado conforme documentado. Se o executor tiver sido coletado pelo GC sem shutdown() (gh-152967), ou um trabalhador de substituição não puder ser iniciado, os futures restantes agora falham com BrokenProcessPool em vez de nunca resolver. A saída de um trabalhador em corrida com shutdown(wait=False) também não pode mais fazer o thread de gerenciamento do executor falhar.

  • gh-150579: O concurrent.futures agora usa importações preguiçosas para seus submódulos executores em vez de um hook __getattr__ do módulo.

  • gh-152951: collections.deque evita falha rara ao chamar extend sob condições de alta pressão de memória.

  • gh-152912: sys.addaudithook() now correctly suppresses only RuntimeError instead of all Exception subclasses when an existing audit hook raises during hook registration. Patch by Yeongu Kim.

  • gh-150880: Normaliza caminhos do Windows não estendidos antes de anexar o curinga usado por os.listdir() e os.scandir(), fazendo com que caminhos com espaços finais se comportem de forma consistente com outras APIs de sistema de arquivos.

  • gh-152068: Corrige um erro quando uma linha era dividida (particularmente no Terminal.app do macOS) no meio de uma palavra reservada colorida, fazendo com que a sequência ANSI Color Reset (ESC0m) não fosse impressa corretamente, fazendo com que a saída ficasse colorida quando não deveria

  • gh-151292: Fix profiling.sampling --binary leaving unreadable profile files when the binary format reaches a size limit. Preserve collected samples when the writer can still finalize safely. Patch by Maurycy Pawłowski-Wieroński.

  • gh-152849: Marcas de data/hora do tipo float e inteiro fora do intervalo agora levantam OverflowError com a mesma mensagem. Patch por tonghuaroot.

  • gh-152847: Rejeita uma regra de transição POSIX TZ com caracteres não-dígitos no campo dia do ano no analisador zoneinfo em Python puro. Patch por tonghuaroot.

  • gh-152905: On glibc, locale.nl_langinfo() now decodes the LC_TIME items (such as the month and day names) using the wide locale data, so the result no longer depends on the LC_CTYPE encoding.

  • gh-152586: tempfile._TemporaryFileWrapper has been renamed to the public tempfile.TemporaryFileWrapper. The old private name is kept as a deprecated alias and will be removed in Python 3.21.

  • gh-152721: Fix quadratic replay time in the profiling.sampling binary reader when a profile’s run-length-encoded samples alternate thread status.

  • gh-77508: Add imaplib.IMAP4.move(), a wrapper for the IMAP MOVE command (RFC 6851), analogous to copy().

  • gh-49680: Add the translate_line_endings parameter to imaplib.IMAP4.append(). By default line endings in the message are translated to CRLF, as before; passing False sends the message literal exactly as given, preserving bare CR or LF octets.

  • gh-152718: Corrige alocação de memória ilimitada no leitor de perfil binário do profiling.sampling quando um arquivo declara mais entradas de string ou quadro do que contém.

  • gh-108280: Conectar o imaplib a um servidor que não envia uma saudação IMAP4 válida (por exemplo, um servidor POP3 respondendo na porta IMAP) agora levanta um erro relatando a resposta do servidor em vez de imaplib.IMAP4.error: None.

  • gh-151126: Corrige uma falha causada pela não definição de MemoryError em caso de falha de alocação ao passar instâncias de ctypes.Structure ou ctypes.Union por valor para funções externas do ctypes.

  • gh-63121: O imaplib agora atualiza a lista de recursos em cache após um login() ou authenticate() bem-sucedido, usando a resposta CAPABILITY enviada pelo servidor ou, se nenhuma foi enviada, consultando-o, para que os recursos que ficam disponíveis apenas após a autenticação (como ENABLE no Gmail) sejam reconhecidos. Recursos anunciados na saudação do servidor agora também são usados, evitando um comando CAPABILITY redundante.

  • gh-88574: O imaplib não falha mais quando um servidor envia uma linha em branco espúria após os dados contados de um literal, inclusive após um literal que termina uma resposta (como um nome de caixa de correio retornado por LIST). Tais linhas em branco agora são puladas sem engolir a linha seguinte.

  • gh-152692: Fix annotationlib.type_repr() returning a string such as None.list.append for bound built-in methods, whose __module__ is None. It now returns the qualified name, as it already did for other builtins.

  • gh-152502: Detect the curses mouse interface (getmouse(), has_mouse(), the BUTTON* constants, and others) and the window is_* state-query methods with configure capability probes or library macros instead of gating them on ncurses-specific macros. They are now also available with other curses implementations that provide them, such as NetBSD curses and PDCurses (the latter underpins windows-curses).

  • gh-151842: Corrige uma falha em _interpreters.capture_exception() quando ocorre MemoryError. Patch por Amrutha Modela.

  • gh-40038: O imaplib agora volta a colocar argumentos de comando entre aspas quando necessário, por exemplo, nomes de caixa de correio contendo um espaço. Tais aspas foram desativadas inadvertidamente quando o módulo foi portado para o Python 3, e os argumentos agora são colocados entre aspas de acordo com a gramática da RFC 3501. Para retrocompatibilidade, um argumento já envolto em aspas duplas é deixado inalterado, para que o código que coloca argumentos entre aspas por conta própria continue funcionando.

  • gh-50966: Corrige recursão ilimitada no turtle quando um manipulador de eventos de mouse que move a tartaruga é reentrado enquanto a tela está sendo redesenhada, por exemplo com screen.ondrag(turtle.goto). Isso podia anteriormente fazer o interpretador falhar.

  • gh-152638: Deprecate tkinter.filedialog.askopenfiles(). Opening several files at once is error-prone and the returned list cannot be used in a with statement; iterate over the names returned by tkinter.filedialog.askopenfilenames() and open them one by one instead.

  • gh-152587: In tkinter, the name parameter of the wait_variable(), setvar() and getvar() methods and the value parameter of setvar() are now required. Their former default values ('PY_VAR' and '1') were not meaningful.

  • gh-152569: Corrige o asyncio.wait() vazando tarefas em espera através do grafo de await (await-graph) ao disputar com um future que nunca se resolve. A tarefa em espera agora é descartada do conjunto awaited_by de cada future uma vez que wait() retorna, mesmo para futures pendentes.

  • gh-110357: Importar hashlib não registra mais um erro no stderr quando um algoritmo de hash normalmente garantido não está disponível no ambiente de execução atual (por exemplo, sob uma configuração OpenSSL FIPS ou uma compilação usando --without-builtin-hashlib-hashes). O código que realmente usa o algoritmo ausente ainda obtém um ValueError claro.

  • gh-152503: Fix curses.window.in_wch(), curses.window.in_wchstr() and curses.window.getbkgrnd() returning garbage text when curses is built against a curses library that does not NUL-terminate the cchar_t text array (such as NetBSD curses).

  • gh-152356: Corrige um travamento em profiling.sampling run --blocking no Windows quando o processo de destino sai. O perfilador agora finaliza perfis binários em vez de continuar a amostrar o processo finalizado.

  • gh-152470: The wide-character curses functions and methods curses.window.get_wch(), curses.window.get_wstr(), curses.unget_wch(), curses.erasewchar(), curses.killwchar() and curses.wunctrl() now also work when Python is not built against a wide-character-aware curses library, on an 8-bit locale, where each character is a single byte in the relevant encoding. curses.ungetch() now also accepts a one-character string, like curses.unget_wch(); on a wide-character build it can be any character (previously a multibyte character raised OverflowError).

  • gh-78335: Atualiza as docstrings das classes de widgets de tkinter e tkinter.ttk para listar todas as opções de widgets suportadas, incluindo opções adicionadas no Tk 9.0 e 9.1. tkinter.Menubutton e tkinter.Message anteriormente não tinham lista de opções.

  • gh-152431: Corrige asyncio.StreamWriter.start_tls() para manter o transporte vinculado do StreamReader em sincronia com o transporte atualizado.

  • gh-103878: The tkinter.filedialog functions that return a filename (askopenfilename(), asksaveasfilename() and askdirectory()) now consistently return an empty string when the dialog is cancelled, instead of an empty tuple or b'' on some platforms. askopenfilenames() likewise always returns an empty tuple, and askopenfiles() an empty list.

  • gh-151126: Corrige duas falhas na inicialização dos módulos tkinter e socket sob pressão de memória. Define o MemoryError ausente.

  • gh-133031: curses.textpad.Textbox now supports entering and reading back the full Unicode range, including combining characters, when curses is built with wide-character support.

  • gh-133031: O curses.textpad.Textbox agora insere e lê de volta os caracteres não-ASCII de uma codificação da localidade de 8 bits, em vez de corrompê-los com uma máscara de 7 bits.

  • gh-43699: The drag cursor in tkinter.dnd is now changed only once the pointer starts moving rather than on the initial button press, so that a plain click no longer flashes it.

  • gh-50409: Deprecate the tagOrId parameter of tkinter.PanedWindow.paneconfigure() (and its paneconfig() alias) in favor of child, for consistency with the other pane methods; it will be removed in Python 3.18.

  • gh-152409: Fix the trace command-line tool not saving the --file counts when --no-report is used, which prevented accumulating counts over several runs. Patch by tonghuaroot.

  • gh-71880: A classe curses.textpad.Textbox agora permite editar a célula do canto inferior direito da janela. Escrever nela usando addch() fazia o cursor ultrapassar o final da janela, gerando um erro e provocando a rolagem de uma janela rolável; por isso, a operação agora é realizada com insch(), que mantém o cursor na mesma posição.

  • gh-152334: Add the curses.define_key(), curses.key_defined() and curses.keyok() key-management functions.

  • gh-152332: Add the curses.term_attrs() function, the counterpart of curses.termattrs() for the WA_* attributes.

  • gh-87904: The curses types and exceptions now report their public module in __module__, repr() and help() – for example curses.window instead of _curses.window and curses.panel.error instead of _curses_panel.error.

  • gh-152325: Add the curses.has_mouse() function and the curses.window.mouse_trafo() method.

  • gh-121249: Deprecate using 'F' and 'D' type codes in the struct module.

  • gh-152275: The curses module now raises OverflowError instead of silently truncating an out-of-range value: curses.color_pair() rejects a color pair number that does not fit in the chtype color field, and the attr argument of the character-cell and attribute methods (addch(), addstr(), attron(), attrset() and others) is checked against the chtype range.

  • gh-83274: Desalocar uma aplicação tkinter de uma thread diferente daquela em que foi criada não faz mais o interpretador falhar. Em vez disso, o interpretador Tcl subjacente vaza e um RuntimeWarning é relatado.

  • gh-81954: Deleting a writable, open zipfile.ZipFile now emits a ResourceWarning. Use as a context manager or call close() explicitly.

  • gh-152305: Corrige a implementação de datetime.time.strftime() em Python puro levantando AttributeError para as diretivas de ano. Patch por tonghuaroot.

  • gh-88758: tkinter.Misc.focus_get(), focus_displayof(), focus_lastfor() e winfo_containing() agora retornam None em vez de levantar KeyError quando o widget não foi criado pelo tkinter (por exemplo, um menu destacado).

  • gh-152260: Add the curses functions scr_dump(), scr_restore(), scr_init() and scr_set(), which dump the whole screen to a file and restore it.

  • gh-38464: tkinter.Misc.nametowidget() agora resolve os nomes gerados automaticamente de menus clonados (um menu usado como barra de menu ou cascata) de volta ao widget original.

  • gh-152263: Add the soft-label-key functions to the curses module: slk_init(), slk_set(), slk_label(), slk_refresh(), slk_noutrefresh(), slk_clear(), slk_restore(), slk_touch(), slk_attron(), slk_attroff(), slk_attrset(), slk_attr(), slk_attr_on(), slk_attr_off(), slk_attr_set() and slk_color().

  • gh-116946: The internal _tkinter tkapp and tktimertoken types now implement the garbage collector protocol, so reference cycles involving a Tcl interpreter or a timer handler can be collected.

  • gh-152258: Add the curses window method dupwin(), which returns a new window that is an independent duplicate of an existing one.

  • gh-152248: Faz com que os analisadores C e em Python puro do zoneinfo validem abreviações POSIX TZ de forma consistente, rejeitando abreviações sem aspas com caracteres não alfabéticos e abreviações entre aspas vazias. Patch por tonghuaroot.

  • gh-80937: Corrige um vazamento de memória no tkinter quando um comando Tcl criado com createcommand não era explicitamente removido antes que o interpretador fosse excluído. O comando não mantém mais o interpretador vivo através de um ciclo de referência.

  • gh-111330: Update pure-Python io.BytesIO to close cleanly when the data has an export such as a memoryview.

  • gh-152246: Corrige o analisador do zoneinfo em Python puro aceitando uma regra de transição POSIX TZ inválida com um separador que não é ponto. Patch por tonghuaroot.

  • gh-152233: Add the curses.complexstr type, an immutable string of styled character cells (the counterpart of curses.complexchar), and the curses window method in_wchstr() that returns one. The string-cell methods addstr(), addnstr(), insstr() and insnstr() now also accept a complexstr. Like curses.complexchar, it works whether or not Python was built against a wide-character-aware curses library.

  • gh-152233: Add the curses.complexchar type, representing a styled character cell (text, attributes and color pair), and the curses window methods in_wch() and getbkgrnd() that return one. The character-cell methods (addch(), bkgd(), border(), hline() and others) now also accept a complexchar. This works whether or not Python was built against a wide-character-aware curses library; on a narrow build a cell holds a single character representable as one byte in the window’s encoding.

  • gh-152099: asyncio’s loop.sendfile(..., fallback=False) now consistently raises asyncio.SendfileNotAvailableError for fallback-only transports, such as SSL/TLS transports, when native sendfile cannot be used. Previously, this case raised RuntimeError.

  • gh-151496: Corrigido profiling.sampling --gecko com --async-aware achatando as pilhas de tarefas assíncronas antes de gerar amostras do Gecko. --binary agora rejeita --async-aware até que o formato binário suporte dados de tarefas assíncronas.

  • gh-152219: Add the curses window methods attr_get(), attr_set(), attr_on(), attr_off() and color_set(), which use a separate color pair argument instead of packing it into the attribute value, and the corresponding WA_* attribute constants.

  • gh-139816: Corrige um travamento no tkinter no Python interativo compilado sem readline. Uma exceção levantada em um callback não faz mais o laço de eventos parar e esperar que o usuário pressione Enter; funções de retorno pendentes agora continuam rodando até que a entrada esteja realmente disponível no stdin.

  • gh-139145: Corrige um laço ocupado no tkinter no Python interativo. Quando um comando Tcl executando seu próprio laço de eventos (como vwait ou wait_variable()) estava ativo e a entrada chegava no stdin, o laço de eventos continuava girando a 100% de CPU. O manipulador de arquivo stdin é agora removido assim que a entrada está disponível. Baseado em um patch por Michiel de Hoon.

  • gh-152204: Fix the pure-Python implementations of datetime.date.fromisoformat(), datetime.time.fromisoformat() and datetime.datetime.fromisoformat() silently accepting some malformed ISO 8601 strings, such as non-ASCII digits or a sign in a fixed-width field (for example '2020+12' or '20201212T0102٣٤'). Each field is now required to be exactly N ASCII digits, matching the C implementation.

  • gh-152212: Corrige o analisador em Python puro do zoneinfo aceitando uma string POSIX TZ com uma abreviação std, mas sem deslocamento. Isso é inválido de acordo com o POSIX e agora levanta ValueError, correspondendo ao acelerador C. Patch por tonghuaroot.

  • gh-152156: Corrige uma possível falha em concurrent.interpreters.create() sob condições de memória limitada.

  • gh-152157: As implementações C de fromisoformat() e fromisoformat() agora rejeitam um separador decimal que não seja seguido por nenhum dígito fracionário antes de um designador de fuso horário.

  • gh-151763: Corrige falha em _interpqueues.create() quando MemoryError acontece na criação da fila.

  • gh-151669: No Windows, ao popular arquivos tar a partir do conteúdo do sistema de arquivos, para se adequar ao padrão do formato tar, contrabarras em alvos de links simbólicos são substituídas por barras simples.

  • gh-105895: Adiciona match e case à lista de tópicos suportados por help().

  • gh-151378: Corrige um erro no coletor binário do Tachyon que causava crescimento ilimitado de memória ao perfilar uma thread que permanecia adormecida. Patch por Maurycy Pawłowski-Wieroński.

  • gh-152074: Increase the buffer size to 256 KiB in asyncio.loop.sendfile() method fallback.

  • gh-152100: Support set operations and nested sets in regular expression character classes, as described in Unicode Technical Standard #18: set difference ([A--B]), intersection ([A&&B]) and union ([A||B]).

  • gh-152079: Corrige datetime.datetime.fromisoformat() na implementação C descartando a parte de sub-segundos de um deslocamento UTC cuja parte inteira de segundos é zero, correspondendo à implementação em Python puro.

  • gh-152052: O acelerador C do json agora relata corretamente uma string não terminada para um escape \uXXXX no final da entrada.

  • gh-152060: Corrige datetime.datetime.fromisoformat() levantando AssertionError em vez de ValueError para algumas strings malformadas na implementação em Python puro, correspondendo à implementação C.

  • gh-152056: Optimize matching of a character set that contains a single character category, such as [\d] or [^\s]: it is now compiled to a single CATEGORY opcode, the same as the corresponding \d or \S escape, instead of being wrapped in an IN block. This speeds up matching and reduces the size of the compiled byte code. Patch by Pieter Eendebak.

  • gh-152033: Optimize matching of character class escapes (\d, \D, \s, \S, \w and \W) that occur outside a character set: they are now compiled to a single CATEGORY opcode instead of being wrapped in an IN block. This speeds up patterns such as \d+ and reduces the size of the compiled byte code.

  • gh-143990: tkinter.font.Font can now wrap a font description without creating a new named font, by passing it as font with exists=True and no name. This avoids a loss of precision in actual(), measure() and metrics(). Keyword options now override the corresponding settings of the given font instead of being ignored.

  • gh-127802: Os métodos descontinuados tkinter.Variable trace_variable(), trace(), trace_vdelete() e trace_vinfo() estão agora programados para remoção no Python 3.17.

  • gh-126219: Corrigida uma falha em tkinter.Tk quando className contém um caractere não-BMP e o tkinter é construído com Tcl/Tk 8.x. Tal nome é agora rejeitado com um ValueError.

  • gh-101284: tkinter.OptionMenu now accepts arbitrary tkinter.Menubutton options as keyword arguments and uses them to override its default appearance.

  • gh-143070: Automatically generated tkinter widget names now start with "+" instead of "!", so that they can be used as tags in the tkinter.Canvas and tkinter.Text widgets.

  • gh-151955: Permite que mais tipos sejam usados no argumento bound para typing.ParamSpec e typing.TypeVarTuple.

  • gh-151920: Add the ttk.Style.theme_styles method, wrapping the Tk ttk::style theme styles subcommand, which returns the list of styles defined in a theme.

  • gh-95555: Regular expressions now support Unicode property escapes \p{...} and \P{...} for properties that the engine can resolve without the unicodedata database: many General_Category values, a number of binary properties, the POSIX compatibility classes, and properties derivable from the code point.

  • gh-151910: Added tkinter.ttk.Treeview methods wrapping the enhanced ttk::treeview widget commands added in Tk 9.1 (and the detached query added in Tk 9.0): item navigation and queries, opening, hiding, sorting and searching of items, and cell focus, selection and tagging. The expand() and collapse() methods (without recursion) also work on Tk older than 9.1.

  • gh-151890: Add the format parameter to the tkinter.PhotoImage.put() method, the metadata parameter to the put(), read(), write() and data() methods, and the withalpha parameter to the get() method. The metadata and withalpha parameters require Tcl/Tk 9.0 or newer.

  • gh-151888: Add the tkinter.PhotoImage.redither() method, wrapping the photo image redither Tk command.

  • gh-151886: Add the tkinter.Misc.tk_appname(), tkinter.Misc.tk_useinputmethods() and tkinter.Misc.tk_caret() methods, wrapping the tk appname, tk useinputmethods and tk caret Tk commands.

  • gh-151881: Add the tkinter.Menu.postcascade() method and the tkinter.Misc.tk_scaling() and tkinter.Misc.tk_inactive() methods, wrapping the postcascade, tk scaling and tk inactive Tk commands.

  • gh-151878: Add the validate() method to the tkinter.Entry and tkinter.Spinbox widgets, forcing an evaluation of the validation command.

  • gh-151876: Add the tkinter.Canvas methods rchars() and rotate(), wrapping the rchars and rotate Tk canvas commands.

  • gh-151874: Add the tkinter methods Misc.winfo_isdark(), Wm.wm_iconbadge() and Wm.wm_stackorder(), wrapping the winfo isdark, wm iconbadge and wm stackorder Tk commands.

  • gh-59396: The tkinter.filedialog.FileDialog dialog and its tkinter.filedialog.LoadFileDialog and tkinter.filedialog.SaveFileDialog subclasses, which follow the layout of the classic Motif file selection dialog, were modernized to match its look and feel more closely. They are now built from the themed tkinter.ttk widgets instead of the classic tkinter widgets, and gained a use_ttk parameter that selects between the classic Tk widgets and the themed ttk widgets. The buttons and field labels gained Alt key accelerators, the default ring follows the keyboard focus, and the Escape key cancels the dialog. The directory and file lists gained a horizontal scrollbar and type-ahead selection. The dialog is now centered over its parent, and the overwrite confirmation of SaveFileDialog uses a themed message box.

  • gh-86165: Corrige imaplib.Time2Internaldate() para usar o deslocamento do fuso horário local para valores de time.struct_time com tm_gmtoff definido como None, conforme retornado por datetime.datetime.timetuple(). Contribuição de Xiao Yuan.

  • gh-151822: Colorize exit, quit, copyright, help, and clear as commands in the REPL when typed alone on a line. Patch by Bartosz Sławecki.

  • gh-59396: The tkinter.simpledialog dialogs were modernized to match the look and feel of the native Tk dialogs. tkinter.simpledialog.SimpleDialog and the askinteger(), askfloat() and askstring() dialogs are now built from the themed tkinter.ttk widgets instead of the classic tkinter widgets; the tkinter.simpledialog.Dialog base class still defaults to the classic widgets for compatibility. Both Dialog and SimpleDialog gained a use_ttk parameter that selects between the classic Tk widgets and the themed ttk widgets. SimpleDialog also gained bitmap and detail parameters, draws the standard icons with themed images in the ttk version, and accepts mappings of button options as buttons entries, where an underline option adds an Alt key accelerator. The font and wrap length of the message and the detail message are taken from the Tk option database and can be overridden by the application. The dialogs also follow the keyboard conventions of the Tk message box: the default ring follows the keyboard focus, the Return key activates the focused button, and the Dialog OK and Cancel buttons gained Alt key accelerators. Several bugs were also fixed.

  • gh-151814: Corrige crescimento ilimitado de memória em io.TextIOWrapper ao escrever repetidamente uma string vazia.

  • gh-133998: Fix tarfile.open() in streaming write mode (w|gz) raising struct.error when given an mtime outside the range of the gzip header’s 32-bit timestamp field. Out-of-range values are now stored as 0, matching gzip.

  • gh-75666: Corrige um vazamento de referência no tkinter: os comandos Tcl criados para funções de retorno de eventos são agora excluídos quando uma ligação é substituída ou desvinculada.

  • gh-151770: Corrige datetime.datetime.fromisoformat() levantando AssertionError em vez de ValueError para um mês fora do intervalo combinado com um horário 24:00.

  • gh-151776: Add curses functions and window methods that report state which could previously only be set: the window methods is_cleared(), is_idcok(), is_idlok(), is_immedok(), is_keypad(), is_leaveok(), is_nodelay(), is_notimeout(), is_pad(), is_scrollok(), is_subwin(), is_syncok(), getdelay(), getparent() and getscrreg(), and the functions curses.is_cbreak(), curses.is_echo(), curses.is_nl() and curses.is_raw(). They are only available when built against an ncurses with NCURSES_EXT_FUNCS.

  • gh-151774: Add the curses functions curses.alloc_pair(), curses.find_pair(), curses.free_pair() and curses.reset_color_pairs() for dynamic color-pair management. They are only available when Python is built against a wide-character version of the underlying curses library with extended-color support.

  • gh-151757: The curses character-cell window methods now accept a full character cell – a spacing character optionally followed by combining characters – in addition to a single integer or byte character. Add the wide-character read methods curses.window.get_wstr() and curses.window.in_wstr(), and the functions curses.erasewchar(), curses.killwchar() and curses.wunctrl(). On a narrow (non-ncursesw) build the character cell holds a single character without combining marks, representable as one byte in the window’s encoding, and curses.window.in_wstr() returns its decoded text.

  • gh-151744: Add curses.nofilter(), which undoes the effect of curses.filter().

  • gh-90092: Add support for multiple terminals to the curses module: the new functions curses.newterm(), curses.set_term() and curses.new_prescr(), the corresponding screen object, and the curses.window.use() method.

  • gh-151675: Add the sync() and pendingsync() methods of tkinter.Text, wrapping the Tk sync and pendingsync subcommands.

  • gh-151674: Add the edit_canundo() and edit_canredo() methods of tkinter.Text, wrapping the Tk edit canundo and edit canredo subcommands.

  • gh-151627: Fix a crash in collections.OrderedDict iterators in free-threaded builds when the dictionary is concurrently cleared or updated.

  • gh-151695: Corrige um uso-após-liberação no módulo curses. A codificação da tela inicial, usada por curses.unctrl() e curses.ungetch() para codificar caracteres não-ASCII, é agora mantida como uma cópia privada em vez de um ponteiro emprestado para um objeto de janela que pode ser desalocado.

  • gh-151596: Adiciona o argumento posicional size ausente à implementação em Python puro de io.TextIOBase.readline().

  • gh-151640: Corrige uma corrida de dados em io.BytesIO em construções com threads livres quando leituras de buffer completo ou espiadas (peeks), ou getvalue(), compartilham o buffer interno com escritas concorrentes.

  • gh-151615: Fix asyncio servers repeatedly logging and rescheduling on a single event loop iteration when accept() fails with a resource errors.

  • gh-151613: Corrige outra maneira pela qual o cache de quadros do perfilador Tachyon podia produzir rastreamentos de pilha mistos impossíveis quando endereços de _PyInterpreterFrame são reutilizados, validando âncoras de quadro armazenadas em cache com um contador de sequência.

  • gh-148660: Corrige uma falha em collections.OrderedDict.copy() quando o __eq__ de uma chave ou o método de uma subclasse altera o dict durante a cópia. Agora levanta RuntimeError em seu lugar, como faz a iteração.

  • gh-151497: Abrir um arquivo tarfile não tenta mais pré-alocar um buffer enorme quando um membro manipulado ou truncado reinivindica um cabeçalho estendido sobredimensionado (um nome longo/link GNU ou um cabeçalho pax). O cabeçalho estendido é agora lido em blocos delimitados, de modo que seu campo de tamanho não pode mais disparar exaustão de memória.

  • gh-151485: Fix command quoting in subprocess.CalledProcessError. Contributed by Benjy Wiener.

  • gh-151436: Fix skewed stack traces in the Tachyon profiler when caching is enabled and when generators and coroutines are profiled, by updating tstate->last_profiled_frame at every frame-removal site. The issue resulted in total erasure of some callers. Patch by Maurycy Pawłowski-Wieroński.

  • gh-151426: Corrige rastreamentos de pilha impossíveis (chamadores e chamados cruzados, órfãos e linhas incorretas) no perfilador Tachyon ao armazenar quadros em cache, tirando um instantâneo (snapshot) dos blocos de pilha antes de percorrer a cadeia de quadros em uma falha de cache. Patch por Maurycy Pawłowski-Wieroński.

  • gh-151403: Corrigida uma falha em subprocess.Popen (e _posixsubprocess.fork_exec) quando o __fspath__() de um item de argv altera concorrentemente a sequência args sendo convertida.

  • gh-151390: Coloriza match no REPL quando seguido por um operador unário + ou -. Patch por Bartosz Sławecki.

  • gh-151128: Cross-language keyword suggestions are now shown for SyntaxError messages. For example, switch x: suggests match, delete x suggests del, function f(): suggests def. Contributed by Zang Langyan.

  • gh-151126: Evita falha por MemoryError não definido na falha de alocação em ctypes.get_errno().

  • gh-151416: Corrige uma falha em os.spawnv() e os.spawnve() quando o método __fspath__() de um item de argv altera a lista argv durante a conversão de argumentos. Erros de conversão de argumento de os.spawnv() diferentes de TypeError, como o ValueError para um nulo embutido, não são mais substituídos por um TypeError genérico.

  • gh-151337: Evita possível vazamento de memória em tkinter.c no Windows.

  • gh-150285: pydoc now uses all available space (80 columns) for formatting reprs of module and class data, but ensure that they do not overflow.

  • gh-151126: Corrige uma falha quando o MemoryError em os._path_splitroot() não foi definido adequadamente.

  • gh-149671: Restaura a compatibilidade com arquivos setuptools -nspkg.pth no módulo site. Injeta a variável sitedir no quadro que executa o código pth. Patch por Victor Stinner.

  • gh-119710: Corrige o subprocesso wait() de asyncio travando quando o processo saiu, mas um de seus pipes é mantido aberto por um processo filho herdado (então o pipe nunca atinge o EOF). O wait() agora retorna assim que o processo sai, independentemente do estado dos pipes.

  • gh-151295: Corrigida uma falha (uso-após-liberação) em bytes.join() e bytearray.join() que podia ocorrer se o __buffer__() de um item alterasse concorrentemente a sequência sendo unida. A alteração é agora relatada como um RuntimeError.

  • gh-109940: Corrige a ativação do venv no Windows no cmd.exe para respeitar VIRTUAL_ENV_DISABLE_PROMPT.

  • gh-117807: Fix mimetypes initialization from MIME map files containing invalid UTF-8 bytes.

  • gh-151179: Corrige um vazamento de pidfd em _PidfdChildWatcher no Linux: o observador não vaza mais o descritor de arquivo do processo quando waitpid() falha com um erro diferente de ChildProcessError.

  • gh-80384: weakref.ref() and weakref.proxy() now raise TypeError if the callback argument is not callable or None.

  • gh-150771: Corrige mensagens do email criadas com conjuntos de caracteres shift_jis ou euc-jp. set_content() agora armazena a carga útil usando o conjunto de caracteres de saída (iso-2022-jp) para que a impressão da mensagem não levante mais UnicodeEncodeError.

  • gh-150285: pydoc now wraps long single-line summary in text output.

  • gh-151049: ipaddress: fix is_global and is_private for the 2001:1::3/128 (DNS-SD Service Registration Protocol Anycast) address, which IANA registered as globally reachable per RFC 9665. It is now correctly reported with is_global True and is_private False.

  • gh-151039: Corrige uma falha quando tipos estáticos de datetime sobrevivem ao módulo _datetime.

  • gh-151042: Fixed venv exporting mixed path styles to PATH on Windows inside fish (via Cygwin, MinGW or MSYS2)

  • gh-151021: Corrige mmap.mmap.find() e rfind() para retornar -1 ao pesquisar por uma subsequência vazia com uma posição inicial além do final do mapeamento.

  • gh-151022: Corrige rastreamentos de pilha do _remote_debugging para objetos de código com tabelas de linhas grandes.

  • gh-150994: Torna as anotações de tipo no módulo privado _colorize resolvíveis.

  • gh-143768: venv: Replace a dangling interpreter symlink in an existing virtual environment instead of failing or silently leaving it broken. Fix by Clay Dugo.

  • gh-62825: Codificações “KS_C_5601-1987”, “KS X 1001”, etc agora são aliases de “CP949” em vez de “EUC-KR”.

  • gh-150913: Corrige a atribuição de fatia em sqlite3.Blob para levantar TypeError e IndexError para inconsistências de tipo e tamanho, respectivamente, mesmo quando a fatia de destino está vazia.

  • gh-140006: The venv activate.fish script now calls fish builtins through builtin so a user function that shadows ./source, echo, printf, set_color, or functions can no longer hijack the virtual environment prompt or break exit-status reporting.

  • gh-143008: Corrige condições de corrida ao re-inicializar um objeto io.TextIOWrapper.

  • gh-150889: Speed up unicodedata.normalize() for the NFC and NFKC forms of non-ASCII text up to a factor 2.

  • gh-150898: Unconditionally assume ssl.SSLContext.keylog_filename exists.

  • gh-150886: Remove the private, undocumented function importlib._bootstrap._object_name(). It had no caller after load_module() and its deprecation warnings were removed from importlib.

  • gh-150583: Define corretamente o nível de compressão padrão em compression.zstd ao passar um dicionário digerido durante a compressão.

  • gh-150866: Fix asyncio.loop.shutdown_asyncgens() to report any BaseException raised during asynchronous generator cleanup.

  • gh-150662: Corrige o coletor --gecko em profiling.sampling que mantinha todas as amostras na memória. Agora ele escreve dados de amostra e marcador em arquivos temporários e os lê de volta, construindo o arquivo de saída no final. Patch por Pablo Galindo e Maurycy Pawłowski-Wieroński.

  • gh-150820: Speed up json.dumps() for small documents. Patch by Bernát Gábor.

  • gh-150818: Speed up logging.getLogger() with a lock-free fast path that returns an already-registered logger without acquiring the logging lock. Patch by Bernát Gábor.

  • gh-150817: Speed up the |, & and ^ operations on enum.Flag members. Patch by Bernát Gábor.

  • gh-150750: Corrige uma condição de corrida em collections.deque.index() com threads livres.

  • gh-150751: http.client now validates the Content-Length header and the chunked chunk-size against the RFC 9112 grammar (1*DIGIT and 1*HEXDIG) before parsing them, rejecting values such as +5, 5_0 or a 0x-prefixed or negative chunk size that int() would otherwise accept. This avoids framing a response differently from a strict peer.

  • gh-150717: Avoid an unnecessary per-call memory allocation when matching re patterns that have no capturing groups. Patch by Bernát Gábor.

  • gh-150685: Atualiza pip empacotado para 26.1.2

  • gh-150641: Corrige erro onde typing.evaluate_forward_ref() com o formato STRING podia vazar nomes internos usados pelo mecanismo de anotações.

  • gh-150942: Speed up re.findall(), re.sub() and re.subn() by appending result items to the output list without an extra reference-count round-trip (using the internal reference-stealing list append helper).

  • gh-150942: Speed up json.loads() decoding of arrays and objects by storing parsed values into the result list/dict without an extra reference-count round-trip (using the internal reference-stealing append/insert helpers).

  • gh-117404: Add a number of constants in modules zlib, bz2, lzma, and compression.zstd, which provide information about the version of libraries that were used for building the module and that are actually loaded. Make compression.zstd.zstd_version_info a named tuple.

  • gh-150478: Add show_jit option to dis.dis to show JIT entry points in the bytecode. This is useful for visualizing where JIT traces are entered from the interpreter.

  • gh-148932: Corrige profiling.sampling em ambientes virtuais Windows para resolver o PID real do Python a partir de um shim de ambiente virtual.

  • gh-150534: Added trigonometric functions that work in units of half turns, rather than radians. The new functions math.acospi(), math.asinpi(), math.atanpi(), and math.atan2pi() return half-turn angles. The new functions math.cospi(), math.sinpi(), and math.tanpi() take half-turn angle arguments. These functions are recommended by IEEE 754-2019 and standardized in C23.

  • gh-150228: A nova classe site.StartupState permite que os chamadores processem em lote arquivos de configuração de inicialização da PEP 829 em múltiplos diretórios de site antes que qualquer código de inicialização execute, com os métodos públicos addsitedir(), addusersitepackages(), addsitepackages() e process(). A assinatura de site.addsitedir() permanece inalterada a partir do Python 3.14. O argumento defer_processing_start_files e a função process_startup_files() adicionados anteriormente no ciclo 3.15 foram removidos; use site.StartupState em seu lugar.

  • gh-150479: email.utils.formataddr() now raises ValueError when the name or address contains a carriage return or line feed, matching email.headerregistry.Address. This check can be disabled by passing strict=False.

  • gh-150449: sqlite3.Blob now supports negative-step slices for reading and writing (e.g. blob[9:0:-2]). Previously, such slices would raise SystemError or ValueError.

  • gh-150406: Corrige uma possível falha ocorrendo durante a inicialização do módulo socket quando o sistema está sem memória em plataformas sem um gethostbyname reentrante.

  • gh-150372: readline: Corrige uma potencial falha durante o autocompletar com Tab causada por um erro de memória esgotada durante a inicialização do módulo.

  • gh-132372: Speed up logging.config.fileConfig() and logging.config.dictConfig() when handling many existing loggers.

  • gh-150157: Corrige uma falha em construções com threads livres que ocorre ao serializar por nome objetos sem um atributo __module__ enquanto sys.modules está sendo modificado concorrentemente.

  • gh-150175: Corrige condição de corrida em unittest.mock.ThreadingMock onde chamadas concorrentes podiam perder incrementos em call_count e outros atributos devido à falta de uma trava em _increment_mock_call.

  • gh-145856: Fix plistlib.dumps() and plistlib.dump() so that skipkeys=True together with sort_keys=True correctly drops non-string keys when the dictionary contains a mix of string and non-string keys. Previously the sort ran before the filter and raised TypeError.

  • gh-84353: Preserva nomes de arquivos codificados em não-UTF-8 ao anexar a um zipfile.ZipFile. Anteriormente, nomes não-ASCII armazenados em uma codificação legada (sem o bit de flag UTF-8 definido) podiam ser corrompidos quando o diretório central era reescrito: eles eram decodificados como cp437 e então re-armazenados como UTF-8.

  • gh-150077: Fix tarfile.TarFile.zstopen to close the underlying zstd file object when opening the tar archive is interrupted by a BaseException subclass such as KeyboardInterrupt.

  • gh-149980: Fix tarfile so that GNU long-name directory entries have all trailing slashes stripped from their names, matching the behavior for short-name entries. Previously, only a single trailing slash was removed.

  • gh-127949: Remove the deprecated asyncio event loop policy system. Patch by Kumar Aditya.

  • gh-149816: Corrige condição de corrida em ssl.SSLContext.sni_callback

  • gh-149189: Reverte as alterações nos padrões do pprint. Patch por Hugo van Kemenade.

  • gh-79413: Update dataclasses.make_dataclass() to add a qualname parameter. The qualname parameter will be used to set the __qualname__ of the created dataclass.

  • gh-149816: Corrige uma potencial condição de uso-após-liberação em pickle.dumps() no modo threads livres ao serializar listas.

  • gh-149995: Atualiza várias docstrings no typing.

  • gh-88726: O pacote email agora usa nomes de conjuntos de caracteres MIME padrão “gb2312” e “big5” em vez de nomes não padrão “eucgb2312_cn” e “big5_tw”.

  • gh-53144: O pacote email agora oferece suporte a todos os apelidos de codecs do Python e usa nomes MIME/IANA para todos os conjuntos de caracteres registrados na IANA.

  • gh-149571: Corrige a implementação C de xml.etree.ElementTree.Element.itertext(): ela não emite mais texto para comentários e instruções de processamento.

  • gh-146406: Add cross-language hints for .clear() on tuple, frozenset, and frozendict, suggesting the mutable counterpart. Follow-up to gh-146406.

  • gh-149921: Corrige vazamentos de referência em caminhos de erro dos módulos de extensão _interpchannels e _interpqueues.

  • gh-149891: Adiciona suporte para mais apelidos de codificação registrados oficialmente na IANA.

  • gh-142349: Adiciona lazy à lista de tópicos suportados por help().

  • gh-149819: Corrige regressão em site.addsitedir() onde arquivos .pth não eram mais processados em subprocessos Python. Isso aconteceu porque site.main() semeou known_paths com entradas herdadas do processo pai, fazendo com que o addsitedir pulasse o processamento do .pth.

  • gh-62259: Add support for multiple multi-byte encodings in the XML parser: “cp932”, “cp949”, “cp950”, “Big5”,”EUC-JP”, “GB2312”, “GBK”, “johab”, and “Shift_JIS”. Add partial support (only BMP characters) for multi-byte encodings “Big5-HKSCS”, “EUC_JIS-2004”, “EUC_JISX0213”, “Shift_JIS-2004”, “Shift_JISX0213”, “utf-8-sig” and non-standard aliases like “UTF8” (without hyphen). The parser now raises ValueError for known unsupported multi-byte encodings such us “ISO-2022-JP” or “raw-unicode-escape” instead of failing later, when encounter non-ASCII data.

  • gh-149816: Corrige uma condição de corrida no método _random.Random.__init__ no modo threads livres.

  • gh-149801: Adiciona nomes registrados na IANA e aliases com zeros à esquerda antes do número (como IBM00858, CP00858, IBM01140, CP01140) para os codecs correspondentes.

  • gh-149473: Chamar os.environ.clear() agora emite o evento de auditoria os._clearenv. Patch por Victor Stinner.

  • gh-149720: Remove support for undotted ext in mimetypes.MimeTypes.add_type().

  • gh-149718: Agrupa quadros de pilha idênticos consecutivos no Tachyon, de modo que os coletor de agregação (pstats, collapsed, flamegraph, gecko) recebam uma única coleta. Melhora a taxa de amostragem em 3x, a taxa de erros e a taxa de falhas caem 70%. Patch por Maurycy Pawłowski-Wieroński.

  • gh-149701: Corrige código de retorno ruim do Lib/venv/bin/activate se o hashing estiver desativado

  • gh-149504: Corrige site.addsitedir() para permitir chamadas reentrantes de dentro de arquivos de inicialização. Anteriormente, um arquivo .pth contendo uma linha import que chamava site.addsitedir() (ou um ponto de entrada .start fazendo o mesmo) podia falhar com RuntimeError: dictionary changed size during iteration durante a inicialização do site, quebrando ferramentas como uv run --with.

  • gh-149584: Corrige sobretaxa excessiva no perfilador Tachyon ao inspecionar um processo remoto, evitando varreduras repetidas do cache de página remoto, agrupando leituras remotas previstas e reutilizando objetos de resultado do perfilador armazenados em cache. Patch por Pablo Galindo e Maurycy Pawłowski-Wieroński.

  • gh-149609: Raise DeprecationWarning on using abc.abstractclassmethod, abc.abstractstaticmethod, and abc.abstractproperty, schedule its removal for Python 3.21.

  • gh-149634: Remove deprecated and unused tarfile.TarInfo.tarfile attribute.

  • gh-149578: Fix tarfile.open() failing with ReadError when opening a PAX format tar archive that contains only global headers and no regular members.

  • gh-139489: Adiciona xml.is_valid_text() ao xml.__all__.

  • gh-149614: Corrige uma regressão que quebrou a capacidade de realizar cópia profunda (deepcopy) em instâncias de argparse.ArgumentParser.

  • gh-149600: Remove deprecated asyncio.iscoroutinefunction() function.

  • gh-149598: Remove support of deprecated strm argument for logging handlers.

  • gh-149595: Remove the sys._enablelegacywindowsfsencoding() function which has been deprecated since Python 3.13.

  • gh-149567: Remove the shutil.ExecError exception which has been deprecated since Python 3.14.

  • gh-112821: No REPL, o autocompletar podia executar código arbitrário no getter de um descritor. Se esse getter levantasse uma exceção, o autocompletar falharia em apresentar qualquer opção para todo o objeto. O autocompletar agora funciona como esperado para esses objetos.

  • gh-149436: Improve performance of inspect.getattr_static().

  • gh-149534: Corrige a fusão de collections.defaultdict e frozendict.

  • gh-149537: Remove kw parameters from python version of functools.reduce() function.

  • gh-80480: Remove deprecated 'u' type code (wchar_t) for the array module. Use 'w' format code instead (Py_UCS4, always 4 bytes).

  • gh-149530: Removed symtable.Class.get_methods() which has been deprecated since 3.14.

  • gh-149528: Remove annotationlib.ForwardRef._evaludate deprecated method.

  • gh-149388: Torna idempotente o fechamento de asyncio.windows_utils.PipeHandle.

  • gh-149499: Removed the sysconfig.expand_makefile_vars() function which has been deprecated since Python 3.14. Use the vars argument of sysconfig.get_paths() instead.

  • gh-149489: Corrige a serialização do ElementTree para HTML. O conteúdo de comentários, instruções de processamento e elementos “xmp”, “iframe”, “noembed”, “noframes” e “plaintext” não é mais escapado. O elemento “plaintext” não tem mais a tag de fechamento. Adiciona suporte a atributos vazios (com valor None).

  • gh-149319: O REPL do asyncio agora ignora PYTHONSTARTUP e PYTHON_BASIC_REPL quando -E ou -I é usado. Patch por Jonathan Dung.

  • gh-149464: Add os.pidfd_getfd() for duplicating a file descriptor from another process via a pidfd. Available on Linux 5.6+. Patch by Maurycy Pawłowski-Wieroński.

  • gh-149056: Corrige json.load() não repassando o argumento array_hook para json.loads(). Patch por Thomas Kowalski.

  • gh-149046: io: Corrige a serialização de io.StringIO: não chama mais str(obj) em subclasses de str. Patch por Thomas Kowalski.

  • gh-118158: Ensure py_compile CLI error messages end with a newline. Contributed by Xiao Yuan.

  • gh-148954: Corrige vulnerabilidade de injeção XML em xmlrpc.client.dumps() onde o methodname não estava sendo escapado antes da interpolação no corpo do XML.

  • gh-148441: xml.parsers.expat: evita uma falha em CharacterDataHandler() quando o tamanho dos dados de caracteres excede o tamanho do buffer do analisador.

  • gh-119670: Add keyword-only parameter force to shlex.quote() to force quoting a string, even if it is already safe for a shell without being quoted.

  • gh-92455: Fix mimetypes to prefer case-sensitive matches for suffix mappings and MIME type suffixes before falling back to case-insensitive matches. Contributed by Xiao Yuan.

  • gh-148736: Fix a latent AttributeError in asyncio call-graph capture when walking an async generator’s ag_await chain: the walker referenced cr_frame instead of ag_frame.

  • gh-148665: A função socket.shutdown agora está ativada para compilações do Emscripten. No entanto, se o runtime não implementar a chamada de sistema shutdown, exibirá o erro “Function not implemented”.

  • gh-148085: Speed up timetuple() and strftime() by caching the time.struct_time and time.strftime lookups, and today() by reading the clock directly instead of calling time.time(). Patching time after importing datetime no longer affects these methods. Patch by Maurycy Pawłowski-Wieroński.

  • gh-147950: Bind yank-arg to M-_ in the REPL.

  • gh-146452: Corrige falha de segmentação (segfault) no pickle ao serializar um dicionário alterado concorrentemente por outra thread na construção com threads livres.

  • gh-47005: Corrige urllib.request.AbstractHTTPHandler.do_open() para dar prioridade aos cabeçalhos regulares definidos via add_header() sobre cabeçalhos não redirecionados, consistente com get_header() e header_items().

  • gh-145107: Simplify asyncio.staggered_race by using eager_start=False.

  • gh-140729: Corrige um erro de serialização com pickle no módulo cProfile ao perfilar um script que usa multiprocessing.Process com os métodos de inicialização spawn e forkserver.

  • gh-143988: Corrigidas falhas em socket.socket.sendmsg() e socket.socket.recvmsg_into() que podiam ocorrer se sequências de buffer fossem alteradas concorrentemente.

  • gh-143008: Fix crash in io.TextIOWrapper when reentrant io.TextIOBase.detach() is called reentrantly from the underlying buffer.

  • gh-81881: shutil.copyfile() now raises SpecialFileError for sockets and device files.

  • gh-140924: Add locale.localize(), locale.delocalize() and platform-specific locale constants from the _locale module to locale.__all__.

  • gh-115634: Corrige um impasse (deadlock) em concurrent.futures.ProcessPoolExecutor ao usar max_tasks_per_child, presente desde que o recurso foi introduzido no Python 3.11. O executor parava de agendar tarefas na fila depois que um processo trabalhador saía ao atingir seu limite de tarefas. Baseado em uma correção proposta por Tabrez Mohammed.

  • gh-140344: The classes ast.slice, ast.ExtSlice, ast.Index, ast.Suite, ast.AugLoad, ast.AugStore, and ast.Param, deprecated since Python 3.9, now issue deprecation warnings on use. They are now scheduled for removal in Python 3.21.

    The dims property of ast.Tuple objects, deprecated since Python 3.9, now issues a deprecation warning when accessed. The property is scheduled for removal in Python 3.21. Use the (non-deprecated) elts property of ast.Tuple objects instead.

    The deprecated global names are also no longer imported by from ast import *.

  • gh-140326: Corrige o espaço de nomes do REPL do asyncio para que importações relativas não sejam mais resolvidas contra o pacote asyncio e __file__ não seja mais definido.

  • gh-139398: Add supported _sunder_ names to the dir() method of the enum module to support them in REPL autocompletion.

  • gh-139819: rlcompleter: Avoid suggesting attributes that are not accessible on instances (e.g., Enum members showing __name__). Patch by Peter (ttw225).

  • gh-79638: Proíbe todo o acesso em urllib.robotparser se o arquivo robots.txt for inalcançável devido a erros de servidor ou rede.

  • gh-86533: A função os.makedirs() e o método pathlib.Path.mkdir() agora têm um parâmetro parent_mode para especificar o modo dos diretórios intermediários ao criar diretórios pais. Isso permite corresponder ao comportamento do Python 3.6 e anterior para os.makedirs().

  • gh-64192: Add the optional buffersize parameter to multiprocessing.pool.Pool.imap() and multiprocessing.pool.Pool.imap_unordered() to limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterables pauses until a result is yielded from the buffer. To fully utilize pool’s capacity when using this feature, set buffersize at least to the number of processes in pool (to consume iterable as you go), or even higher (to prefetch the next N=buffersize-processes arguments).

  • gh-51067: Add remove() and repack() to ZipFile.

  • gh-134261: zip: Em construções reproduzíveis, o ZipFile usa UTC em vez da hora local ao escrever marcas de data/hora nos arquivos para evitar estouro negativo (underflow).

  • gh-133998: Corrige a exceção struct.error ao criar um arquivo com gzip.GzipFile ou comprimir dados com gzip.compress() se o horário do sistema estiver fora do intervalo de 00:00:00 UTC de 1º de janeiro de 1970 a 06:28:15 UTC de 7 de fevereiro de 2106, ou se o argumento mtime passado explicitamente estiver fora do intervalo de 0 a 2**32-1.

  • gh-68164: Fix zipfile.ZipFile.writestr() so it sets the “regular file” bit by default.

  • gh-46927: Prevent readline from overriding the COLUMNS and LINES environment variables, as values are not updated on terminal resize.

  • gh-72902: Optimize (~x1.4 speedup) fractions.Fraction.from_decimal() and fractions.Fraction.from_float() for Decimal and float inputs, respectively. Patch by Sergey B Kirpichev.

  • gh-128110: Corrige erro na análise de cabeçalhos de endereço do email que podia resultar em espaços irrelevantes no texto decodificado ao usar uma política de e-mail moderna. Espaços entre pares de palavras codificadas adjacentes da RFC 2047 agora são ignorados, conforme a seção 6.2 (e consistente com a análise existente de cabeçalhos não estruturados como Subject).

  • gh-129382: The venv.EnvBuilder and venv.create() APIs now use the platform-dependent default for symlinks from venv’s command-line interface.

  • gh-125763: Remove the broken spacebar quit binding from turtledemos sorting_animate example.

  • gh-107398: Corrige exceção no modo de fluxo do tarfile ao processar o arquivo com o campo extra do gzip.

  • gh-121109: Corrige problema de desempenho do tarfile ao ler arquivos no modo de fluxo (ex: r|*).

  • gh-120665: Corrigido um problema onde os carregadores do unittest carregavam e instanciavam subclasses derivadas de unittest.TestCase que também são classes base abstratas, as quais não podem ser instanciadas.

  • gh-115988: lzma adds constants to support the newer BCJ filters for ARM64 and RISC-V.

  • gh-108518: The iterator returned by concurrent.futures.Executor.map() is no longer automatically closed if a function call raises an exception. Use method close() to explicitly close the iterator.

  • gh-113329: Corrige OSError sendo levantada ao tentar executar doctests em objetos de classe no REPL. Patch por Sten Wessel.

  • gh-105708: Aceita um prefixo V maiúsculo em endereços IPvFuture em urllib.parse.urlsplit().

  • gh-103925: Corrige csv.Sniffer.sniff() para uma amostra com terminações de linha \r\n em que um campo entre aspas termina uma linha: uma letra podia ser detectada como o delimitador.

  • gh-60055: Let urllib.robotparser.RobotFileParser accept a urllib.request.Request object as well as a url string when setting a robots.txt url.

  • gh-102967: A bug in doctest._SpoofOut.truncate() was causing None to be passed to StringIO.seek() when no size was given. A simple fix skips the seek call when no size is given so the buffer can be truncated from the current position.

  • gh-91099: imaplib.IMAP4.login() agora levanta exceções com str em vez de bytes. Patch por Florian Best.

  • gh-82039: http.cookiejar.FileCookieJar.load() now checks the first, format signature line in a case-insensitive manner. Patch by Ashley Harvey.

  • gh-101267: Quando um processo trabalhador termina inesperadamente, concurrent.futures.ProcessPoolExecutor agora define uma exceção BrokenProcessPool separada em cada future pendente em vez de compartilhar uma única instância entre todos eles. Compartilhar uma exceção produzia rastreamentos de pilha malformados: cada chamada Future.result() re-levantava o mesmo objeto, anexando outra cópia do rastreamento a ele.

  • bpo-46375: Add io.BytesIO.peek() method to read without advancing position.

  • bpo-47216: Added mtime option to gzip.open(), which will be passed to the constructor of GzipFile.

  • gh-70758: Creating a new turtle screen after the previous one was closed no longer raises turtle.Terminator on the first turtle command.

  • bpo-45509: Os cabeçalhos do Gzip agora são verificados para campos NAME, COMMENT e HCRC corrompidos.

  • gh-75245: socket.socket.makefile() now supports line buffering (buffering=1) in text mode, as open() does and as it worked in Python 2. Previously it silently used block buffering. In binary mode it now emits a RuntimeWarning and uses the default buffer size, also as open() does.

  • bpo-44012: The exploded attribute of ipaddress.IPv6Address and ipaddress.IPv6Interface now supports addresses with a scope ID (link-local addresses). Previously the former raised AddressValueError and the latter omitted the scope ID.

  • bpo-40469: TimedRotatingFileHandler now uses the creation time instead of the last modification time of an existing log file as the basis for the first rotation after handler creation, if supported by the OS and file system. This allows it to be used in short-running programs that start and end before the rotation interval expires.

  • bpo-42861: Add IPv4Network.next_network() and IPv6Network.next_network(). Patch by Faisal Mahmood.

  • gh-84687: The os.exec* functions now set the filename attribute of the raised FileNotFoundError or NotADirectoryError to the program name passed by the caller.

  • gh-83869: Fix tarfile reading an archive with a GNU sparse 1.0 member whose size is set in the pax extended header. The offset of the next header was computed from the offset of the data, which is already past the sparse map, and from the size of the member, which can be the apparent size of the sparse file. All following members were unreachable.

  • gh-61366: http.cookiejar.MozillaCookieJar now reads session cookies written by curl and Wget, which use 0 in the expiration time field. Contributed by Jérémie Detrey.

Documentação

  • gh-57491: Reduz a profundidade do sumário na documentação EPUB de três para dois níveis, tornando-o muito mais curto e fácil de navegar em leitores de e-books.

  • gh-142083: Document the 'w' type code in the array.array docstring, so that it lists the same type codes as array.typecodes and the array module documentation.

  • gh-118150: Esclarece na documentação do difflib o que junk realmente faz, suas desvantagens e como controlá-lo.

  • gh-59551: Rename Doc/library/dialog.rst to tkinter.dialogs.rst.

  • gh-86726: Expande grandemente a documentação do tkinter para cobrir toda a API pública do pacote e seus submódulos. As descrições são orientadas ao Python em vez do Tcl/Tk, com tipos de retorno corrigidos e informações de versionadded/versionchanged.

  • gh-150319: Tipos genéricos embutidos e da biblioteca padrão agora documentam o significado de seus parâmetros de tipo.

  • gh-109503: Corrige a documentação para shutil.move() no uso do os.rename(), já que a movimentação não-atômica pode ser usada mesmo se os arquivos estiverem no mesmo sistema de arquivos. Patch por Fang Li

Testes

  • gh-159211: The iOS testbed no longer gathers simulator diagnostics when a test run fails.

  • gh-158051: O ambiente de testes para iOS foi atualizado para garantir compatibilidade com o Xcode 27.

  • gh-157628: In regrtest, only consider that a test leaks if all test runs leak at least one file descriptor. For example, ignore “[0, 1, -1] file descriptors, sum=0” deltas, instead of reporting a leak. Patch by Victor Stinner.

  • gh-140550: Enable limited C API tests on Free Threading in test_cext and test_cppext: test the Py_TARGET_ABI3T macro. Patch by Victor Stinner.

  • gh-75876: In verbose mode, a test decorated with bigmemtest() now reports how much memory it really used, and the number of major page faults it took, if any.

  • gh-75876: A test decorated with bigmemtest() now runs in a subprocess if it really allocates the memory it asks for (that is, if the -M option is used), so that the memory it uses and the address space it fragments are released when it ends. A dummy run stays in the process. The separate memory watchdog process is no longer needed: the parent process watches the memory usage of the subprocess.

  • gh-109817: Add the --single-process-per-case option to libregrtest to run every test case in a separate process. Test cases from the same test module are run sequentially. This helps to detect order dependencies and environment leaks between test cases.

  • gh-155411: Fix test.support.subTests() for asynchronous test methods. They were wrapped in a synchronous function, which discarded the coroutine without awaiting it, so the test silently did not run at all.

  • gh-108885: Running the Python test suite with -vv now reports every example of a doctest. A single -v reports the test names, as before.

  • gh-132581: The list of tests which altered the execution environment now includes the reasons why the environment was considered altered, for example an unraisable exception or a modified sys.path. The final result no longer repeats the same state twice (like ENV CHANGED then ENV CHANGED).

  • gh-155109: Add test.support.run_with_limited_c_stack() and use it in tests that exhaust the C stack with a fixed number of recursive calls, so that their outcome no longer depends on the C stack size.

  • gh-76595: Adiciona testes de C API para PyCapsule_Import().

  • gh-154211: Adiciona test.support.skip_if_huge_c_stack() e usa-o para pular testes que esgotam a pilha C se o limite da pilha for muito grande (por exemplo, no DragonFly BSD ou com ulimit -s unlimited).

  • gh-154167: O executor de testes (regrtest) agora restaura o manipulador de SIGINT padrão se ele foi herdado como ignorado, para que a suíte de testes não trave mais quando executada como um trabalho em segundo plano do shell.

  • gh-154144: Corrige a construção do módulo _testcapi no NetBSD.

  • gh-154137: Check for Windows handle leaks in regrtest. Patch by Victor Stinner.

  • gh-152548: Adiciona o decorador test.support.isolation.runInSubprocess() para executar um método de teste ou subclasse de TestCase em um subprocesso do interpretador limpo, isolado do restante da execução do teste.

  • gh-151626: Corrige vários testes em test.test_inspect, test.test_import, test.test_importlib, test.test_py_compile e test.test_compileall que falhavam quando a suíte de testes era executada com PYTHONPYCACHEPREFIX definido. Esses testes agora neutralizam o prefixo pycache onde eles assumem o layout de bytecode padrão de __pycache__.

  • gh-151096: Corrige falha no test_embed quando o CPython é configurado com um prefixo de execução dividido (--exec-prefix diferente de --prefix).

  • gh-151130: Adiciona mais testes para a API C PyWeakref_*.

  • gh-150966: Evita terminar prematuramente alvos de teste do perfilador de amostragem ao vivo com falha, o que tornava instáveis as asserções no stderr em buildbots ASAN.

  • gh-150387: Corrige travamento em test.test_profiling.test_sampling_profiler.test_live_collector_ui.TestLiveModeErrors.test_run_failed_script_live em buildbots lentos. O teste agora sempre enfileira uma tecla q final para que o loop da TUI ao vivo saia mesmo quando o perfilador coleta amostras suficientes para entrar no laço de entrada pós-finalizado.

  • gh-150114: On Linux, regrtest now logs the total memory usage of all Python processes. Read the private memory in /proc/pid/smaps. Patch by Victor Stinner.

  • gh-149776: Corrige test_socket no kernel do Linux 7.1 e mais recente: pula testes de UDP Lite se não for suportado. Patch por Victor Stinner.

  • gh-148853: Corrige testes falhando no FreeBSD no in_systemd_nspawn_sync_suppressed() do test.support devido ao diretório /run ilegível.

  • gh-142414: Isolate reloading modules in test_interpreters to avoid having broken references.

Construção

  • gh-158878: Stop creating an empty Modules/Setup.local file as it no longer seems to be required to statically link the extension modules.

  • gh-158683: Fix the Modules/Setup entry for the _zstd module by adding missing source files.

  • gh-129040: Added support for function call adaptor trampolines for wasi to prevent traps when C handlers take the wrong number of arguments. Dropped Emscripten function call adaptors support for JS runtimes that don’t support wasm-gc.

  • gh-158010: Atualiza os scripts de build para Android e iOS para usar o OpenSSL 3.5.9.

  • gh-136872: Python built with --with-address-sanitizer or --with-memory-sanitizer now includes pymalloc, but uses malloc as the default memory allocator. Set PYTHONMALLOC=pymalloc to use pymalloc.

  • gh-157923: Support WASI SDK 34.

  • gh-157549: Usa sysconf(_SC_PAGESIZE) em vez de getpagesize() em remote_debug.h para que _remote_debugging compile no Darwin com -Werror=implicit-function-declaration.

  • gh-157142: Fix the link of Programs/_freeze_module when extension modules are built in (MODULE_BUILDTYPE=static) and the test modules are enabled: Modules/getpath_noop.c now defines _Py_Get_Getpath_CodeObject(), which _testinternalcapi uses.

  • gh-155292: In makeunicodedata.py, the script for updating Unicode data, skip generating stringprep.py if the current interpreter’s Unicode data version does not match the target version.

  • gh-156049: Add --with-hwaddress-sanitizer to build with HWAddressSanitizer.

  • gh-156554: Update PY_SUPPORT_TIER according to PEP 11 for these target triples: aarch64-*-linux-gnu/gcc, aarch64-pc-windows-msvc/msvc, x86_64-apple-darwin*/clang, and powerpc64le-*-linux-gnu/gcc.

  • gh-156244: Update configure to reflect that the riscv64-unknown-linux-gnu target triple is now a PEP 11 tier 3 supported platform.

  • gh-155911: Fix curses detection with libraries in LIBS and --without-curses. Patch by Shamil Abdulaev.

  • gh-156115: Construções do simulador iOS agora são configuradas com -mios-simulator-version-min em vez de -mios-version-min do dispositivo. O sinalizador do dispositivo fazia com que o ligador (link) rejeitasse bibliotecas resolvidas do SDK do simulador, falhando silenciosamente a detecção da biblioteca.

  • gh-156109: iOS builds may now be configured without a framework, producing a static libpython for embedding in an app binary. Such a build cannot load extension modules at runtime, and requires MODULE_BUILDTYPE=static and --disable-test-modules to be requested explicitly. A shared iOS build must still be a framework build.

  • gh-153400: Support os.getrandom() when building Python with old glibc versions and recent Linux kernel (glibc 2.25 or older and Linux kernel 3.17 or newer). Get the syscall number from kernel headers, rather than glibc headers.

  • gh-90604: configure no longer sets MULTIARCH on OpenBSD platforms.

  • gh-152023: Atualiza as construções para Android para o SQLite 3.53.4. Além disso, habilita as funções median() e percentile().

  • gh-154271: Define _XOPEN_SOURCE=600 on Solaris and illumos, so that on illumos the socket module is built with sendmsg(), recvmsg() and the CMSG_* helpers. This also enables the forkserver multiprocessing start method.

  • gh-154136: Fix building the math module on FreeBSD. Define _ISOC23_SOURCE to make the C23 library declarations (such as sinpi() in math.h) visible.

  • gh-154070: Construção do módulo curses contra um ncurses capaz de caracteres largos mesmo quando não for chamado ncursesw – por exemplo, o ncurses pkgsrc no NetBSD e illumos, ou o ncurses do sistema no macOS. Essa biblioteca anteriormente produzia uma compilação estreita.

  • gh-152902: Added Intel icx compiler support to configure.ac. Contributed by High Performance Kernels LLC.

  • gh-154055: The curses and curses.panel modules can now be built against a curses library that lacks the X/Open attr_t and soft-label attribute functions, scr_set() or resizeterm() – such as the native SVr4 curses of illumos and Solaris. These functions are probed and used only when present.

  • gh-136687: Add the --with-curses option to configure to select the curses backend (ncursesw, ncurses or the system’s native curses) or, as --without-curses, to exclude the curses and curses.panel modules from the build.

  • gh-126877: Corrige a verificação do configure para Tcl/Tk, que podia ser bem-sucedida incorretamente com compiladores otimizadores quando as bibliotecas estavam ausentes.

  • gh-153511: Removes the legacy MSI and Nuget build scripts, the legacy py.exe launcher (now replaced by the Python install manager), and adds a PC/layout readme.

  • gh-153438: Atualiza ferramentas e documentação de construção e instalador do Windows para usar a URL de download atual do nuget.exe.

  • gh-152870: Corrige um erro de compilação na extensão C do decimal (_decimal) quando compilada com EXTRA_FUNCTIONALITY. Context.apply() chamava o auxiliar interno _apply usando sua assinatura pré-Argument-Clinic; a chamada agora é feita através da função _impl gerada.

  • gh-152769: Ativa o trampolim do perfilador perf no Alpine Linux com a biblioteca C musl em x86_64 e aarch64. O trampolim é específico da arquitetura e não depende da biblioteca C, portanto o mesmo trampolim em assembly usado para a glibc é reutilizado para a musl.

  • gh-152502: The curses module now detects its optional functions with configure capability probes instead of assuming ncurses, so it builds against narrow (non-wide) ncurses and other curses implementations such as NetBSD curses, exposing exactly the functions they provide.

  • gh-152240: Fix C stack unwinding tests on Linux LoongArch builds by teaching the manual frame pointer unwinder to recognize the LoongArch frame layout.

  • gh-151163: Atualiza construção do Android para incluir SQLite versão 3.53.2.

  • gh-115119: Fix the detection of libmpdec header when no .pc files are available.

  • gh-148294: Corrigido o uso de AC_PATH_TOOL em configure.ac para permitir que um compilador C++ seja encontrado no PATH.

  • gh-131372: Add a --with-build-details-suffix configure flag to allow Linux distributions that co-install multiple versions of Python in the same tree to avoid build-details.json clashes.

  • gh-148260: No Linux, quando o Python está vinculado à biblioteca C musl, usa um tamanho de pilha de thread de pelo menos 1 MiB em vez do padrão da musl, que é 128 kiB. Patch por Victor Stinner.

  • gh-148832: Fix --enable-bolt build by switching the default BOLT flag from -icf=1 to -icf=0. -icf=1 folds address-taken functions and breaks type-slot dispatch, crashing on list and tuple concatenation. Patched by Shamil Abdulaev.

  • gh-144712: Fix _testinternalcapi import failure due to missing _Py_jit_entry symbol when built with --enable-experimental-jit. Patch by Shamil Abdulaev.

  • gh-138800: Corrige o nome da biblioteca no python3.pc no Android.

  • gh-139314: Add the --with-zlib and --with-bzip2 configure options to select the zlib and bzip2 implementations used to build the zlib and bz2 modules. In addition to the default system libraries, they can build against zlib-rs and libbzip2-rs, and --with-zlib=zlib-ng verifies that the detected zlib is zlib-ng. --without-zlib and --without-bzip2 exclude the modules from the build.

  • gh-115119: Removed bundled copy of the libmpdec, use system library if it’s available. Patch by Sergey B Kirpichev.

Windows

  • gh-158010: Construções do Windows atualizadas para usar o OpenSSL 3.5.9.

  • gh-157906: Fix an incorrect architecture macro check that prevented CPU prefetching in the free-threaded garbage collector on 32-bit Windows builds.

  • gh-157789: Use compiler option -Og in case of clang-cl debug builds on Windows to reduce stack usage. Patch by Chris Eibl.

  • gh-157368: Corrige o truncamento de sys.version para versões do clang-cl 22 ou mais recentes no Windows. Também corrige o caso do Windows em Arm, onde o compilador da Microsoft era relatado em vez do clang. Patch por Chris Eibl.

  • gh-157212: Corrige a compilação de _Py_ThreadId() no Windows ARM64 com toolchains MinGW, onde __getReg() não está disponível. O endereço do TEB agora é lido diretamente de x18. Patch por Christian Aurich.

  • gh-152433: Allow build socket module for Universal Windows Platform.

  • gh-68048: Creating a mmap.mmap object on Windows no longer resets the position of the underlying file to zero, as on other platforms.

  • gh-85470: Importing ctypes on Windows no longer loads user32.dll, which made the system treat the process as a GUI process and stop sending logoff and shutdown console control events to it. ole32.dll, which pulled user32.dll in, is now delay loaded.

  • gh-72353: Reading from the console on Windows now continues if the read was cancelled by Ctrl+C, but the SIGINT handler did not raise an exception. Previously the read ended as if at end of file.

  • gh-86427: Fix the encoding of the standard streams in the legacy Windows stdio mode (PYTHONLEGACYWINDOWSSTDIO). It is now the encoding of the device the stream is connected to, as in Python 3.7, not the ANSI code page.

  • gh-87587: os.device_encoding() on Windows now returns the code page of any console file descriptor, not only 0, 1 and 2, and returns None for other character devices like NUL. The UTF-8 code page is now reported as "utf-8" instead of "cp65001".

  • gh-152023: Atualiza as construções para Windows para o SQLite 3.53.4. Além disso, habilita as funções median() e percentile().

  • gh-152433: Changed winreg to conditional import for Universal Windows Platform compatibility.

  • gh-69573: msvcrt.putch() and msvcrt.putwch() now check the return value of the underlying _putch() and _putwch() C functions and raise OSError on failure, for example when the process has no console attached, instead of silently ignoring the error.

  • gh-124111: Atualiza as compilações do Windows para usar Tcl/Tk 9.0.4.

  • gh-152433: Modernize fileutils removing GetFileInformationByHandle API calls and allow build for Universal Windows Platform.

  • gh-152433: Allow build ceval.c for Windows UWP.

  • gh-152433: Allow build _overlapped module for Universal Windows Platform.

  • gh-152433: _winapi module: improve UWP compatibility

  • gh-152433: make dynload_win.c UWP compatible.

  • gh-152433: Allow build _ctypes for Universal Windows Platform.

  • gh-152433: ssl: improve UWP build compatibility.

  • gh-152433: _winapi: implement GetVersion() UWP alternative.

  • gh-152433: Fix errors in sys.getwindowsversion() for Universal Windows Platform build.

  • gh-152433: Restores the mmap module when CPython is built from source for specific Windows API sets.

  • gh-152433: Use the Windows API GetFileSizeEx() for memory mapped files, rather than the older GetFileSize().

  • gh-152433: Implement os.cpu_count() for Universal Windows Platform.

  • gh-151163: Atualiza construções do Windows para incluir SQLite versão 3.53.2.

  • gh-150836: Faz o tkinter instalado funcionar com construções Tcl/Tk 9 que embutem a biblioteca de scripts Tk na DLL do Tk no Windows.

  • gh-149786: Corrige inicializadores de ambiente virtual em construções com threads livres do Windows.

  • gh-138489: As distribuições do Windows agora incluem um arquivo build-details.json (veja PEP 739). O instalador legado não o instala, mas todas as outras distribuições do python.org e todas as configurações predefinidas no script PC\layout incluirão um.

  • gh-140146: Impede que o tkinter trave no Windows se o stdin for redirecionado para um encadeamento (pipe) em uma sessão interativa. Isso é útil para testar o uso interativo do tkinter a partir de um script, por exemplo como parte da suíte de testes do cpython.

  • gh-86768: os.lseek() and seek() of file objects now raise OSError for pipes on Windows, and seekable() now returns False for them. Previously seeking a pipe silently appeared to succeed. As a consequence, opening a pipe in a read-write binary mode ('r+b' or 'w+b') now raises io.UnsupportedOperation unless buffering is disabled.

  • bpo-40851: subprocess.Popen with shell=True on Windows now honors wShowWindow of the startupinfo argument, so the console window of the started program can be shown. Previously it was always hidden.

macOS

  • gh-158010: Atualiza o instalador do macOS para usar o OpenSSL 3.5.9.

  • gh-152023: Atualiza o construções do instalador do macOS para usar o SQLite 3.53.4.

  • gh-124111: Atualiza o instalador do macOS para usar o Tcl/Tk 9.0.4.

  • gh-152023: Atualiza as construções do instalador do macOS para SQLite 3.53.3. Ativa as funções median() e percentile().

  • gh-151163: Atualiza o instalador do macOS para incluir SQLite versão 3.53.2.

  • gh-150644: Quando o registro do sistema (system logging) está ativado (com config.use_system_logger), as mensagens agora são marcadas como públicas. Isso permite que o registrador do sistema do macOS 26 veja as mensagens sem configuração especial.

IDLE

  • gh-158067: Corrige a caixa de diálogo File Open (“Abrir Arquivo”) do IDLE para que liste arquivos de texto antes de arquivos Python ao ser aberta a partir do console ou de uma janela de saída.:

  • gh-56596: Faz com que os atalhos de teclado do IDLE que utilizam letras ASCII funcionem com o Caps Lock ativado, mesmo quando apenas uma das versões (maiúscula ou minúscula) estiver definida.

  • gh-75512: A saída de uma thread, exibida no console IDLE enquanto uma instrução está sendo digitada, não mais se sobrepõe ao prompt da instrução.

  • gh-64007: O IDLE não aplica mais coloração de sintaxe ao texto inserido para input() no Console.

  • gh-85560: Corrige a falha do IDLE em encontrar o parêntese de abertura quando uma linha de continuação dentro dos parênteses começa com else de uma expressão condicional ou com yield.

  • gh-75487: Corrige o salvamento de um número truncado quando um campo de número inteiro na caixa de diálogo de configurações do IDLE é esvaziado usando a tecla Backspace.

  • gh-74112: Ctrl-C in the IDLE Shell now interrupts blocking calls such as time.sleep() and socket.recv.

  • gh-151471: Colorize the soft keyword type in IDLE.

  • gh-103089: IDLE no longer hangs when opening a file with very long lines. Only the first 2,000 characters of a line are colorized.

  • gh-89544: Corrige o travamento do IDLE após reiniciar o console enquanto recebe uma saída grande do processo do usuário.

  • gh-70331: IDLE no longer fails to start with python -m idlelib, and its user process no longer fails to start, when the current directory contains user files with the same names as standard library modules that IDLE imports, such as random.py or tkinter.py.

  • gh-93016: Fix parsing of command line arguments in the IDLE “Run… Customized” dialog on Windows: backslashes are no longer treated as escape characters. Fix also display of the previous arguments in the dialog.

  • gh-59568: Corrige as caixas de diálogo “Save As” (“Salvar como”) e “Open” (“Abrir”) no IDLE para arquivos cujos nomes começam com ~ no Windows e no X11, ao utilizar versões do Tcl/Tk anteriores à 9.

  • gh-69004: O item “Debugger” do menu “Debug” do IDLE agora fica desabilitado enquanto o código do usuário é executado, assim como o “Stack Viewer”.

  • gh-69365: As caixas de diálogo de pesquisa do IDLE agora exibem um erro de expressão regular abaixo do campo de entrada, em vez de em uma caixa de mensagem.

  • gh-93966: O destaque de um erro de sintaxe no Console do IDLE agora é removido quando a próxima instrução é inserida, e não apenas quando ocorre o próximo erro de sintaxe.

  • gh-105689: Corrige as dicas de chamada (calltips), a correspondência de parênteses e a indentação automática no Console IDLE após a exibição de uma saída contendo aspas ou parênteses desbalanceados.

  • gh-60402: No IDLE, pressionar Tab em uma string que não esteja no início de um nome de arquivo insere uma tabulação em vez de abrir a lista de preenchimento automático.

  • gh-68453: Corrigida a execução do IDLE com a opção -s em conjunto com -c, -r ou -: o comando ou script agora é executado após o arquivo de inicialização, sem exibir uma caixa de diálogo de erro e sem reiniciar o console.

  • gh-75234: Corrige as fontes de ajuda de edição e as associações de tecla na caixa de diálogo de configurações do IDLE após selecioná-los com o teclado.

  • gh-69919: IDLE now reports any exception raised by compiling the source, such as MemoryError for too deeply nested source, instead of hanging the Shell.

  • gh-91398: Remove the border around the IDLE Shell sidebar, which was drawn in the window background color and stood out with dark themes.

  • gh-71136: Fix a hang of the IDLE Shell when code run under the debugger raises KeyboardInterrupt.

  • gh-154511: Consolida o tratamento da roda do mouse do IDLE em idlelib.util. A função wheel_event é transferida de idlelib.tree para lá e junta-se a x11_buttons — que indica se o Tk reporta rotações da roda a um widget como eventos <Button-4>/<Button-5> — e a bind_wheel, que associa os eventos enviados pelo Tk.

  • gh-156896: Para de excluir submódulos do tkinter quando idlelib.run for importado.

  • gh-153480: Fix IDLE failing to start when opening a file which does not exist yet. Fix a traceback when a file open in the IDLE editor is deleted by another program; IDLE now asks whether to close the window, save the file elsewhere, or ignore it.

  • gh-55646: Corrige a falha do IDLE na inicialização quando a configuração do usuário contém uma associação de teclas inválida, como <Alt-Key-up> em vez de <Alt-Key-Up>. A associação inválida agora é ignorada, com a emissão de um aviso.

  • gh-82183: Quando o shell está ocupado executando código, usar “Run… Customized” com “Restart shell” desmarcado agora relata que o shell está executando em vez de reiniciá-lo de qualquer maneira.

  • gh-83653: Deixar em branco uma entrada inteira na caixa de diálogo Configurações do IDLE, como “Auto squeeze min lines”, não salva mais uma string vazia como um valor de configuração inválido.

  • gh-65339: Salvar o Shell do IDLE ou uma janela de saída agora usa como padrão a extensão .txt e lista arquivos de texto antes de arquivos Python, já que seu conteúdo não é código-fonte Python.

  • gh-80504: O campo “In files:” da caixa de diálogo Find in Files do IDLE agora sempre contém um caminho de diretório completo, mesmo para um editor não salvo ou para o Shell. Isso mostra na saída do grep qual diretório foi pesquisado.

  • gh-134300: Não adiciona o diretório idlelib ao caminho do processo de usuário do IDLE. O código do usuário executado no IDLE não pode mais importar submódulos do idlelib como módulos de nível superior, como import help.

  • gh-89360: Corrige uma falha rara no editor IDLE quando a janela de autocompletar é fechada: excluir uma vinculação de chave para uma sequência que não está vinculada ao evento virtual é agora ignorado em vez de levantar um ValueError.

  • gh-66172: O IDLE não falha mais ao iniciar quando um arquivo de configuração do usuário está corrompido. O arquivo ilegível é renomeado com o sufixo “.bad”, as configurações padrão são utilizadas em seu lugar e um aviso lista os arquivos afetados.

  • gh-71956: Corrige o Replace All na caixa de diálogo Substituir do editor IDLE quando a direção de pesquisa é “Up” e “Wrap around” está desligado: agora substitui todas as correspondências acima da posição atual em vez de apenas a primeira.

  • gh-152728: Move as funções run.fix_scaling, editor.fixwordbreaks (como fix_word_breaks) e pyshell.fix_x11_paste para idlelib.util.

  • gh-66331: Define a propriedade de janela WM_CLASS das janelas do IDLE como Idle no X11, para que os gerenciadores de janelas as agrupem e e listem corretamente em vez de usar o Toplevel padrão.

  • gh-85320: O IDLE agora lê e escreve seus arquivos de configuração e o arquivo de pontos de interrupção (breakpoints) usando UTF-8 em vez da codificação da localidade. Isso evita que dados não-ASCII (como caminhos não-ASCII) sejam corrompidos e torna os arquivos portáveis entre ambientes.

  • gh-90304: Impede que o IDLE falhe ao iniciar quando uma fonte relata largura zero para o caractere '0'. Esse tipo de fonte defeituosa causava um ZeroDivisionError; agora, o editor utiliza a largura configurada como alternativa.

  • gh-135511: Fix display of NameError and AttributeError with multi-line message.

  • bpo-6699: Avisa o usuário se um arquivo for sobrescrito ao salvar.

Ferramentas/Demos

  • gh-158451: python-gdb.py is now able to format an invalid Unicode string: render invalid characters as \Uhhhhhhhh instead of raising an exception. Patch by Victor Stinner.

  • gh-156261: Argument Clinic: the pid_t, uid_t, gid_t, Py_off_t, HANDLE, DWORD and BOOL converters, previously defined in individual files, are now provided by Argument Clinic itself.

  • gh-156219: Fix Argument Clinic generating code which reads an optional positional argument which was not passed, if the function has a **kwds parameter.

  • gh-113318: The value of a setter generated by Argument Clinic is now a parameter, which can use a converter, and a getter can define a return converter. It is optional to declare the value of the setter. The accessors of the same attribute are now identified by the Python name of that attribute instead of the C basename, so they can use different C basenames, and several implementations of the same accessor can be defined in different preprocessor conditional blocks.

  • gh-113318: Correção na Clínica de Argumentos para @getter e @setter dentro de um bloco condicional de pré-processador; anteriormente, ocorria um erro interno. A Clínica de Argumentos agora também rejeita acessores de um mesmo atributo que possuam nomes base em C diferentes, bem como o mesmo acessor definido duas vezes — situações que, silenciosamente, geravam entradas inválidas ou duplicadas de PyGetSetDef.

  • gh-155373: Argument Clinic now generates the inlined code of the converters for functions with optional groups, instead of a PyArg_ParseTuple() call for every number of arguments. Every argument is now parsed once, most such functions now use the fastcall convention, and the errors for a wrong type of an argument are the same as in other functions.

  • gh-64660: Argument Clinic return converters no longer need to hardcode the name of the variable returned by the parsing function. It is now available as data.parser_retval.

  • gh-155266: Fix Argument Clinic for a function whose only parameter is in an optional group. It generated METH_O, which made the argument mandatory and did not pass the flag of the group.

  • gh-64595: Argument Clinic now touches the source file if a file generated from it was changed, and keeps the generated files newer than the source file. The build system does not know that the source file depends on the files generated from it, so it did not recompile the source file if only the generated file was changed.

  • gh-155263: Add the --list option to Argument Clinic. It prints the modules, classes and functions which Argument Clinic defines in the specified files, each function with its signature.

  • gh-107570: Argument Clinic: report errors on the offending line. Errors in a docstring were reported on the line which ends the block, and errors detected when generating the code were reported without any position.

  • gh-108270: Argument Clinic: add support for deprecating a parameter with the [until X.Y] marker. Passing such argument emits a DeprecationWarning.

  • gh-108271: Argument Clinic: add support for parameter aliases. A keyword-only parameter with a default value which shares the C name of a preceding parameter declares an alternative name for it.

  • gh-155218: Fix Argument Clinic generating the flags of the optional groups in different order on 32-bit and 64-bit platforms.

  • gh-155212: The --converters option of Argument Clinic now accepts file names and can be used with --make. It prints the converters and return converters which the specified files define, instead of the built-in ones.

  • gh-155207: Argument Clinic now supports the --dry-run and --diff options. They list the files which would be changed, or write a unified diff of the changes to the standard output, without modifying any file.

  • gh-64502: Argument Clinic now supports several optional groups on the same nesting level, like in [y, x,] [n,] attr. Such groups can be omitted independently of each other.

  • gh-64502: Fix Argument Clinic support of parameters with a default value used together with optional groups. Such parameters were always required in the generated parsing code.

  • gh-154580: Corrige python-gdb.py levantando UnicodeEncodeError ao exibir formatadamente (pretty-printing) uma str não-ASCII em uma localidade cujo conjunto de caracteres do host não pode codificá-la, como qualquer string não-ASCII na localidade C.

  • gh-154059: Corrige as unidades de tempo nas dicas de ferramentas do gráfico de chama (flamegraph) do Tachyon, levando em consideração o intervalo de amostragem ao converter amostras para milissegundos.

  • gh-153804: Add Tools/inspection/oracle_external_inspection.py, a harness for measuring the accuracy of Tachyon. It reports impossible-stack rates, speed, error rates and the statistical distance from the blocking non-cached best reference on selected snippets. Patch by Maurycy Pawłowski-Wieroński.

  • gh-152384: Os pacotes CPython Pixi agora estão todos acessíveis no mesmo subdiretório Tools/pixi-packages, em vez de Tools/pixi-packages/{variant} como antes. As variantes agora são selecionadas não via subdiretório, mas via flags; veja https://pixi.prefix.dev/latest/concepts/package_specifications/#extras-and-flags para instruções de uso. A variante tsan-freethreading foi renomeada para tsan_freethreading, enquanto as variantes default, asan e freethreading mantêm seus nomes anteriores.

  • gh-150258: Atualiza a dica de ferramenta no gráfico de chama do Tachyon para mostrar porcentagens absolutas e relativas.

  • gh-87613: Add a @vectorcall decorator to Argument Clinic to generate O protocolo vectorcall parsing code for object.__init__() and object.__new__().

  • gh-130647: Add --omit-header option to pygettext.

  • gh-111501: PS1 is no longer exported by venv activate script

API C

Python 3.15.0 beta 1

Release date: 2026-05-07

Segurança

  • gh-149254: Update Android and iOS installer to use OpenSSL 3.5.6.

  • gh-149017: Update bundled libexpat to version 2.8.0.

  • gh-148252: Fixed string table and sample record bounds checks in _remote_debugging when decoding certain .pyb inputs on 32-bit builds. Patch by Maurycy Pawłowski-Wieroński.

  • gh-90309: Base64-encode values when embedding cookies to JavaScript using the http.cookies.BaseCookie.js_output() method to avoid injection and escaping.

  • gh-148808: Added buffer boundary check when using nbytes parameter with asyncio.AbstractEventLoop.sock_recvfrom_into(). Only relevant for Windows and the asyncio.ProactorEventLoop.

  • gh-148395: Fix a dangling input pointer in lzma.LZMADecompressor, bz2.BZ2Decompressor, and internal zlib._ZlibDecompressor when memory allocation fails with MemoryError, which could let a subsequent decompress() call read or write through a stale pointer to the already-released caller buffer.

  • gh-148252: Fixed stack depth calculation in _remote_debugging when decoding certain .pyb inputs on 32-bit builds. Issue originally identified and diagnosed by Tristan Madani (@TristanInSec on GitHub).

  • gh-148178: Hardened _remote_debugging by validating remote debug offset tables before using them to size memory reads or interpret remote layouts.

  • gh-148169: A bypass in webbrowser allowed URLs prefixed with %action to pass the dash-prefix safety check.

  • gh-146581: Fix vulnerability in shutil.unpack_archive() for ZIP files on Windows which allowed to write files outside of the destination tree if the patch in the archive contains a Windows drive prefix. Now such invalid paths will be skipped. Files containing “..” in the name (like “foo..bar”) are no longer skipped.

  • gh-137586: Fix a PATH-injection vulnerability in webbrowser on macOS where osascript was invoked without an absolute path. The new MacOS class uses /usr/bin/open directly, eliminating the dependency on osascript entirely.

  • gh-146333: Fix quadratic backtracking in configparser.RawConfigParser option parsing regexes (OPTCRE and OPTCRE_NV). A crafted configuration line with many whitespace characters could cause excessive CPU usage.

  • gh-146211: Reject CR/LF characters in tunnel request headers for the HTTPConnection.set_tunnel() method.

Núcleo e embutidos

  • gh-148940: Revert the process size based deferral of garbage collection (gh-133464). The performance issue this change resolves is also fixed by gh-142562. This approach has the problem that process size as seen by the OS (e.g. the resident size or RSS) does not immediately decrease after cyclic garbage is freed since mimalloc defers returning memory of the OS. This change applies to the free-threaded GC only.

  • gh-149243: Check for recursion limits in CALL_ALLOC_AND_ENTER_INIT opcode.

  • gh-126910: Add support for unwinding JIT frames using GNU backtrace. Patch by Diego Russo and Pablo Galindo

  • gh-149171: Allow assignment to the __module__ attribute of typing.TypeAliasType instances.

  • gh-149122: Fix a crash in optimized calls to all(), any(), tuple(), list(), and set() with an async generator expression argument (for example, tuple(await x for x in y)). These calls now correctly raise TypeError instead of crashing.

  • gh-149049: Fix stack underflow for BINARY_OP in tier 2.

  • gh-83065: Fix a deadlock that could occur when one thread is importing a submodule (for example import pkg.sub.mod) while another thread is importing one of its parent packages (for example import pkg.sub) and that parent’s __init__.py itself imports the submodule. The import system now acquires module locks in hierarchical (parent-before-child) order so the two threads serialise instead of raising _DeadlockError.

  • gh-113956: Fix a data race in sys.intern() in the free-threaded build when interning a string owned by another thread. An interned copy owned by the current thread is used instead when it is not safe to immortalize the original.

  • gh-148850: Fix the memory sanitizer false positive in os.getrandom().

  • gh-148820: Fix a race in _PyRawMutex on the free-threaded build where a Py_PARK_INTR return from _PySemaphore_Wait could let the waiter destroy its semaphore before the unlocking thread’s _PySemaphore_Wakeup completed, causing a fatal ReleaseSemaphore error.

  • gh-148829: Add sentinel, implementing PEP 661. PEP by Tal Einat; patch by Jelle Zijlstra.

  • gh-146270: Fix a sequential consistency bug in structmember.c.

  • gh-148766: The interpreter help (such as python --help) is now in color. Patch by Hugo van Kemenade.

  • gh-148571: Fix a crash in the JIT optimizer when specialized opcode families inherited incompatible recorded operand layouts.

  • gh-148653: Forbid marshalling recursive code objects, slice and frozendict objects which cannot be correctly unmarshalled.

  • gh-142516: Forward-port the generational cycle garbage collector to the default 3.15 build, replacing the incremental collector while leaving the free-threaded collector unchanged.

  • gh-146462: Added PyTypeObject.tp_basicsize, PyTypeObject.tp_dictoffset, and PyHeapTypeObject.ht_cached_keys offsets to _Py_DebugOffsets to support version-independent read-only dict introspection tools.

  • gh-145239: Unary plus is now accepted in match literal patterns, mirroring the existing support for unary minus. Patch by Bartosz Sławecki.

  • gh-148515: Fix a bug in the JIT optimizer reading operands for uops with multiple caches.

  • gh-148390: Fix an undefined behavior in memoryview when using the native boolean format (?) in cast(). Previously, on some common platforms, calling memoryview(b).cast("?").tolist() incorrectly returned [False] instead of [True] for any even byte b. Patch by Bénédikt Tran.

  • gh-148418: Fix a possible reference leak in a corrupted TYPE_CODE marshal stream.

  • gh-148393: Fix data races between PyDict_Watch() / PyDict_Unwatch() and concurrent dict mutation in the free-threaded build.

  • gh-148398: Fix a bug in the JIT optimizer where class attribute loads were not invalidated after type mutation.

  • gh-146527: Add a GCMonitor class with a get_gc_stats method to the _remote_debugging module to allow reading GC statistics from an external Python process without requiring the full RemoteUnwinder functionality. Patch by Sergey Miryanov and Pablo Galindo.

  • gh-148284: Fix high stack consumption in Python’s interpreter loop on Clang 22 by setting function limits for inlining when building with computed gotos.

  • gh-148037: Remove critical section from PyCode_Addr2Line() in free-threading.

  • gh-115802: Improve JIT code generation on Linux AArch64 by reducing the indirect call to external symbols. Patch by Diego Russo.

  • gh-148189: Repaired undercount of bytes in type-specific free lists reported by sys._debugmallocstats(). For types that participate in cyclic garbage collection, it was missing two pointers used by GC.

  • gh-148222: Fix vectorcall support in types.GenericAlias when the underlying type does not support the vectorcall protocol. Fix possible leaks in types.GenericAlias and types.UnionType in case of memory error.

  • gh-148208: Fix recursion depth leak in PyObject_Print()

  • gh-95004: The specializing interpreter now specializes for enum.Enum improving performance and scaling in free-threading. Patch by Kumar Aditya.

  • gh-149202: Enable frame pointers by default for GCC-compatible CPython builds, including -mno-omit-leaf-frame-pointer, -marm on 32-bit ARM, and/or -mbackchain on s390x platforms when the compiler supports them, so profilers and debuggers can unwind native interpreter frames more reliably. Users can pass --without-frame-pointers to ./configure to opt out.

  • gh-148014: Accept a function name in -X presite command line option and PYTHON_PRESITE environment variable. Patch by Victor Stinner.

  • gh-147998: Fixed a memory leak in interpreter helper calls so cleanup works when an operation falls across interpreter boundaries. Patch by Maurycy Pawłowski-Wieroński.

  • gh-146455: Fix O(N²) compile-time regression in constant folding after it was moved from AST to CFG optimizer.

  • gh-146306: Specialize float true division in the tier 2 optimizer with inplace mutation for uniquely-referenced operands.

  • gh-142186: Global sys.monitoring events can now be turned on and disabled on a per code object basis. Returning DISABLE from a callback disables the event for the entire code object (for the current tool).

  • gh-126910: Add support for unwinding JIT frames using GDB. Patch by Diego Russo and Pablo Galindo.

  • gh-146031: The unstable API _PyInterpreterState_SetEvalFrameFunc has a companion function _PyInterpreterState_SetEvalFrameAllowSpecialization to specify if specialization should be allowed. When this option is set to 1 the specializer will turn Python -> Python calls into specialized opcodes which the replacement interpreter loop can choose to respect and perform inlined dispatch.

  • gh-145278: The encodings is now partially frozen, including the aliases and utf_8 submodules.

    The linecache is now frozen.

  • gh-134584: Optimize and eliminate redundant ref-counting for MAKE_FUNCTION in the JIT.

  • gh-143886: Reorder function annotations so positional-only arguments are returned before other arguments. This fixes how functools.singledispatch() registers functions with positional-only arguments.

  • gh-98894: Restore function__entry and function__return DTrace/SystemTap probes that were broken since Python 3.11.

  • gh-116021: Support for creating instances of abstract AST nodes from the ast module is deprecated and scheduled for removal in Python 3.20. Patch by Brian Schubert.

  • gh-137814: Fix the __qualname__ attribute of __annotate__ functions on functions.

  • gh-137600: ast: The constructors of AST nodes now raise a TypeError when a required argument is omitted or when a keyword argument that does not map to a field on the AST node is passed. These cases had previously raised a DeprecationWarning since Python 3.13. Patch by Brian Schubert.

  • gh-137293: Fix SystemError when searching ELF Files in sys.remote_exec().

  • gh-135357: Add support for socket.SO_PASSRIGHTS on Linux.

  • gh-134690: Removed deprecated in PEP 626 since Python 3.12 codeobject.co_lnotab from types.CodeType.

  • gh-100239: Specialize BINARY_OP for concatenation of lists and tuples, and propagate the result type through _BINARY_OP_EXTEND in the tier 2 optimizer so that follow-up type guards can be eliminated.

Biblioteca

  • gh-148823: Defer the import of _colorize in argparse until needed for coloring output.

  • gh-141560: Add an annotation_format parameter to inspect.getfullargspec().

  • gh-139489: Add the xml.is_valid_text() function, which allows to check whether a string can be used in the XML document.

  • gh-142389: Add backticks to stdlib argparse help to display in colour. Patch by Hugo van Kemenade.

  • gh-149377: Update bundled pip to 26.1.1

  • gh-142389: Add backtick markup support in argparse option help text to highlight inline code when color output is enabled. Patch by Hugo van Kemenade.

  • gh-148675: Remove F and D formats from array and memoryview. Patch by Victor Stinner.

  • gh-149342: Fix _remote_debugging binary writing so that sampling a thread whose Python frame stack is empty (for example while it is in a C call or mid-syscall) no longer raises RuntimeError("Invalid stack encoding type"), and so that BinaryWriter.total_samples after finalize() or context-manager exit includes samples flushed from the RLE buffer. Patch by Maurycy Pawłowski-Wieroński.

  • gh-149010: The inspect module CLI now reports as much information as it has available for non-source modules when --details is specified, and provides an error message rather than a traceback when --details is omitted. It also reports improved information when the given target location is not the target’s defining location and when the given target is a data value rather than a class or function definition.

  • gh-146609: Use argparse for colour help timeit CLI. Patch by Hugo van Kemenade.

  • gh-142389: Add backticks for colour to regrtest and pdb’s help description. Patch by Hugo van Kemenade.

  • gh-144384: Lazily import _colorize. Patch by Hugo van Kemenade.

  • gh-149321: Fix import cycles exposed by running standard library modules with -X lazy_imports=none.

  • gh-145378: Generate consistent colors for pdb commands in pdb REPL.

  • gh-149296: Add a dump subcommand to profiling.sampling that prints a single traceback-style snapshot of a running process’s Python stack, including per-thread status, source line highlighting, optional bytecode opcode names, and async-aware task reconstruction. Patch by Pablo Galindo.

  • gh-143231: A module attribute has been added to warnings.WarningMessage.

  • gh-148675: ctypes: Change the _type_ of c_float_complex, c_double_complex and c_longdouble_complex from F, D and G to Zf, Zd and Zg for compatibility with numpy. Patch by Victor Stinner.

  • gh-148675: The array.typecodes type changed from str to tuple to support type codes longer than 1 character (Zf and Zd). Patch by Victor Stinner.

  • gh-149221: Catch rare math domain error for random.binomialvariate().

  • gh-149231: In tomllib, the number of parts in TOML keys is now limited.

  • gh-143231: unittest.TestCase.assertWarns() and unittest.TestCase.assertWarnsRegex() no longer swallow warnings that do not match the specified category or regex. Nested context managers are now supported.

  • gh-149214: Fix _remote_debugging misreading non-ASCII Unicode strings (Latin-1, BMP and non-BMP) from a remote process. Filenames and function names that contain non-ASCII characters are now reported correctly in stack traces, the sampling profiler, and asyncio task introspection.

  • gh-149189: pprint now uses modern defaults: indent=4 and width=88, and the default compact=False output is now formatted similar to pretty-printed json.dumps(), with opening parentheses and brackets followed by a newline and the contents indented by one level. The expand parameter, added in 3.15.0a8, has been removed; compact=False (the default) now produces the former expand=True layout. Patch by Hugo van Kemenade.

  • gh-149173: Fix inverted PYTHON_BASIC_REPL environment check in pdb._pyrepl_available.

  • gh-149117: Fix runpy.run_module() and runpy.run_path() to set the name attribute on the ImportError they raise.

  • gh-149148: ensurepip: Upgrade bundled pip to 26.1. This version fixes the CVE 2026-3219 vulnerability. Patch by Victor Stinner.

  • gh-149009: Validate that profiling.sampling binary profiles do not contain more unique (thread, interpreter) pairs than declared in the header. Patch by Maurycy Pawłowski-Wieroński.

  • gh-148292: ssl: Update ssl.SSLSocket and ssl.SSLObject for OpenSSL 4. The classes now remember if they get a ssl.SSLEOFError. In this case, following read(), sendfile(), write(), and do_handshake() calls raise ssl.SSLEOFError without calling the underlying OpenSSL function. Thanks to that, ssl.SSLSocket behaves the same on all OpenSSL versions on EOF. Patch by Victor Stinner.

  • gh-149085: Add a max_threads keyword argument to faulthandler.dump_traceback(), faulthandler.dump_traceback_later(), faulthandler.enable(), and faulthandler.register().

  • gh-148641: pkgutil.resolve_name() gets a new optional, keyword-only argument called strict. The default is False for backward compatibility.

  • gh-148093: Fix an out-of-bounds read of one byte in binascii.a2b_uu(). Raise binascii.Error, instead of reading past the buffer end.

  • gh-149083: dataclasses.MISSING and dataclasses.KW_ONLY are now instances of sentinel.

  • gh-148914: Fix memoization of in-band PickleBuffer in the Python implementation of pickle. Previously, identical PickleBuffers did not preserve identity, and empty writable PickleBuffer memoized an empty bytearray object in place of b'', so the following references to b'' were unpickled as an empty bytearray object.

  • gh-149026: Add colour to pickletools CLI output. Patch by Hugo van Kemenade.

  • gh-148991: Add colour to tokenize CLI output. Patch by Hugo van Kemenade.

  • gh-138907: Support RFC 9309 in urllib.robotparser.

  • gh-148981: Add color parameter to ast.dump().

  • gh-148849: Deprecate http.cookies.Morsel.js_output() and http.cookies.BaseCookie.js_output(), which will be removed in Python 3.19. Use http.cookies.Morsel.output() or http.cookies.BaseCookie.output() instead.

  • gh-146311: Add a canonical keyword-only parameter to the base32, base64, base85, ascii85, and Z85 decoders in base64 and binascii. When true, encodings with non-zero padding bits (base32/64) or non-canonical encodings (base85/ascii85) are rejected. Single-character final groups in binascii.a2b_ascii85() and binascii.a2b_base85() are now always rejected as encoding violations, regardless of canonical; previously they were silently ignored and produced no output bytes.

  • gh-148947: Fix crash in @dataclasses.dataclass with slots=True that occurred when a function found within the class had an empty __class__ cell.

  • gh-148680: ForwardRef objects that contain internal names to represent known objects now show the type_repr of the known object rather than the internal __annotationlib_name_x__ name when evaluated as strings.

  • gh-124397: The threading module added tooling to support concurrent iterator access: threading.serialize_iterator, threading.synchronized_iterator(), and threading.concurrent_tee().

  • gh-148801: xml.etree.ElementTree: Fix a crash in Element.__deepcopy__ on deeply nested trees.

  • gh-148735: xml.etree.ElementTree: Fix a use-after-free in Element.findtext when the element tree is mutated concurrently during the search.

  • gh-148740: Fix usage for uuid command-line interface to support a custom namespace be provided for uuid3 and uuid5.

  • gh-148688: bz2, compression.zstd, lzma, zlib: Fix a double free on memory allocation failure. Patch by Victor Stinner.

  • gh-148675: array, struct: Add support for Zd and Zf formats for double complex and float complex. Patch by Victor Stinner.

  • gh-148651: Fix reference leak in compression.zstd.ZstdDecompressor when an invalid option key is passed.

  • gh-148641: PEP 829 (package startup configuration files) implements a new format <name>.start parallel to <name>.pth files, to replace import lines in the latter.

  • gh-148639: Implement PEP 800, adding the @typing.disjoint_base decorator. Patch by Jelle Zijlstra.

  • gh-148615: Fix pdb to accept standard – end of options separator. Reported by haampie. Patched by Shrey Naithani.

  • gh-146553: Fix infinite loop in typing.get_type_hints() when __wrapped__ forms a cycle. Patch by Shamil Abdulaev.

  • gh-148599: Update the socket module’s WSA error messages to match official documentation.

  • gh-148508: An intermittent timing error when running SSL tests on iOS has been resolved.

  • gh-144881: asyncio debugging tools (python -m asyncio ps and pstree) now retry automatically on transient errors that can occur when attaching to a process under active thread delegation. The number of retries can be controlled with the --retries flag. Patch by Bartosz Sławecki.

  • gh-148518: If an email containing an address header that ended in an open double quote was parsed with a non-compat32 policy, accessing the username attribute of the mailbox accessed through that header object would result in an IndexError. It now correctly returns an empty string as the result.

  • gh-148464: Add missing __ctype_le/be__ attributes for c_float_complex and c_double_complex. Patch by Sergey B Kirpichev.

  • gh-148370: configparser: prevent quadratic behavior when a ParsingError is raised after a parser fails to parse multiple lines. Patch by Bénédikt Tran.

  • gh-121190: importlib.resources.files() now emits a more meaningful error message when module spec is None (as found in some __main__ modules).

  • gh-127012: importlib.abc.Traversable.read_text now allows/solicits an errors parameter.

  • gh-137855: Improve import time of dataclasses module by lazy importing re and copy modules.

  • gh-148352: Add more color to calendar’s CLI output. Patch by Hugo van Kemenade.

  • gh-148254: Use singular “sec” instead of “secs” in timeit verbose output for consistency with other time units.

  • gh-130472: Integrate fancycompleter with import completions.

  • gh-148241: json: Fix serialization: no longer call str(obj) on str subclasses. Patch by Victor Stinner.

  • gh-148225: The profiling.sampling replay command now rejects non-binary profile files with a clear error explaining that replay only accepts files created with --binary.

  • gh-148192: email.generator.Generator._make_boundary could fail to detect a duplicate boundary string if linesep was not n. It now correctly detects boundary strings when linesep is rn as well.

  • gh-148207: typing.TypeVarTuple now accepts bound, covariant, contravariant, and infer_variance parameters, matching the interface of typing.TypeVar and typing.ParamSpec.

  • gh-148100: Soft deprecate re.match() and re.Pattern.match() in favour of re.prefixmatch() and re.Pattern.prefixmatch(). Patch by Hugo van Kemenade.

  • gh-147991: Improve tomllib import time (up to 10x faster). Patch by Victor Stinner.

  • gh-147957: Guarantees that collections.UserDict.popitem() will pop in the same order as the wrapped dictionary rather than an arbitrary order.

  • gh-146256: The profiling.sampling module now supports JSONL output format via --jsonl. Each run emits a newline-delimited JSON file that is sequentially parseable by external tools, scripts, and programmatic consumers. Patch by Maurycy Pawłowski-Wieroński.

  • gh-146609: Add colour to timeit CLI output. Patch by Hugo van Kemenade.

  • gh-146563: xml.parsers.expat: add an exception note when a custom Expat handler return value cannot be properly interpreted. Patch by Bénédikt Tran.

  • gh-137586: Add MacOS to webbrowser for macOS, which opens URLs via /usr/bin/open instead of piping AppleScript to osascript. Deprecate MacOSXOSAScript in favour of MacOS.

  • gh-146406: Cross-language method suggestions are now shown for AttributeError on builtin types and their subclasses. For example, [].push() suggests append, (1,2).append(3) suggests using a list, None.keys() suggests expecting a dict, and 1.0.__or__ suggests using an int.

  • gh-146313: Fix a deadlock in multiprocessing’s resource tracker where the parent process could hang indefinitely in os.waitpid() during interpreter shutdown if a child created via os.fork() still held the resource tracker’s pipe open.

  • gh-146292: Add colour to BaseHTTPRequestHandler logs, as used by the http.server CLI. Patch by Hugo van Kemenade.

  • gh-145917: Add MIME types for TTC and Haptics formats to mimetypes. (Contributed by Charlie Lin in gh-145918.)

  • gh-145846: Fix memory leak in _lsprof when clear() is called during active profiling with nested calls. clearEntries() now walks the entire currentProfilerContext linked list instead of only freeing the top context.

  • gh-145831: Fix email.quoprimime.decode() leaving a stray \r when eol='\r\n' by stripping the full eol string instead of one character.

  • gh-145378: Use PyREPL as the default input console for pdb

  • gh-145244: Fixed a use-after-free in json encoder when a default callback mutates the dictionary being serialized.

  • gh-117716: Fix wave writing of odd-sized data chunks by appending the required RIFF pad byte and correcting the RIFF chunk size field accordingly.

  • gh-145200: hashlib: fix a memory leak when allocating or initializing an OpenSSL HMAC context fails.

  • gh-145056: Add support for frozendict in dataclasses.asdict() and dataclasses.astuple().

  • gh-145105: Fix crash in csv reader when iterating with a re-entrant iterator that calls next() on the same reader from within __next__.

  • gh-130750: Restore quoting of choices in argparse error messages for improved clarity and consistency with documentation.

  • gh-137855: Reduce the import time of dataclasses module by ~20%.

  • gh-70647: strptime() now raises ValueError when the format string contains %d without a year directive. Using %e without a year now emits a DeprecationWarning.

  • gh-105936: Attempting to mutate non-field attributes of dataclasses with both frozen and slots being True now raises FrozenInstanceError instead of TypeError. Their non-dataclass subclasses can now freely mutate non-field attributes, and the original non-slotted class can be garbage collected.

  • gh-142831: Fix a crash in the json module where a use-after-free could occur if the object being encoded is modified during serialization.

  • gh-108411: typing.IO and typing.BinaryIO method arguments are now positional-only.

  • gh-130273: Fix traceback color output with Unicode characters.

  • gh-142307: imaplib: deprecate support for IMAP4.file. This attribute was never meant to be part of the public interface and altering its value may result in unclosed files or other synchronization issues with the underlying socket. Patch by Bénédikt Tran.

  • gh-141449: Improve tests and documentation for non-function callables as annotate functions.

  • gh-140287: The asyncio REPL now handles exceptions when executing PYTHONSTARTUP scripts. Patch by Bartosz Sławecki.

  • gh-139489: Add the xml.is_valid_name() function, which allows to check whether a string can be used as an element or attribute name in XML.

  • gh-75707: Add optional mtime argument to tarfile.open(), for setting the mtime header field in .tar.gz archives.

  • gh-125862: The contextlib.contextmanager() and contextlib.asynccontextmanager() decorators now work correctly with generators, coroutine functions, and async generators when the wrapped callables are used as decorators.

  • gh-135528: http.cookiejar: add “tv”, “or”, “nom”, “sch”, and “web” to the default list of supported country code second-level domains.

  • gh-135056: Add a -H or --header CLI option to python -m http.server. Contributed by Anton I. Sipos.

  • gh-134551: Add t-strings support to pprint functions

  • gh-133956: Fix bug where @dataclass wouldn’t detect ClassVar fields if ClassVar was re-exported from a module other than typing.

  • gh-132631: Fix “I/O operation on closed file” when parsing JSON Lines file with JSON CLI.

  • gh-108951: asyncio: Add TaskGroup.cancel which cancels unfinished tasks and exits the group without raising asyncio.CancelledError.

  • gh-123853: Update the table of Windows language code identifiers (LCIDs) used by locale.getdefaultlocale() on Windows to protocol version 16.0 (2024-04-23).

  • gh-122476: The email module no longer incorrectly uses RFC 2047 encoding for a mailbox with non-ASCII characters in its local-part. Under a policy with utf8 set False, attempting to serialize such a message will now raise an HeaderWriteError. There is no valid 7-bit encoding for an internationalized local-part. Use email.policy.SMTPUTF8 (or another policy with utf8=True) to correctly pass through the local-part as Unicode characters.

  • gh-83938: The email module no longer incorrectly uses RFC 2047 encoding for a mailbox with non-ASCII characters in its domain. Under a policy with utf8 set False, attempting to serialize such a message will now raise an HeaderWriteError. Either apply an appropriate IDNA encoding to convert the domain to ASCII before serialization, or use email.policy.SMTPUTF8 (or another policy with utf8=True) to correctly pass through the internationalized domain name as Unicode characters.

  • gh-81074: The email module no longer treats email addresses with non-ASCII characters as defects when parsing a Unicode string or in the addr_spec parameter to email.headerregistry.Address. RFC 5322 permits such addresses, and they were already supported when parsing bytes and in the Address username parameter.

    The (undocumented) email.errors.NonASCIILocalPartDefect is no longer used and should be considered deprecated.

  • gh-70039: Fixed bug where smtplib.SMTP.starttls() could fail if smtplib.SMTP.connect() is called explicitly rather than implicitly.

  • gh-113471: Allow http.server to set a default content-type when serving files with an unknown or missing extension.

  • gh-83281: email: improve handling trailing garbage in address lists to avoid throwing AttributeError in certain edge cases

  • gh-96894: Do not turn echo off for subsequent commands in batch activators (activate.bat and deactivate.bat) of venv.

Documentação

Testes

  • gh-149425: Increase time delta in test.test_zipfile.test_core.OtherTests.test_write_without_source_date_epoch

  • gh-148600: Add OpenSSL 4.0.0 support to test configurations.

Construção

  • gh-149353: Avoid unnecessary JIT-related rebuilds during make install after --enable-optimizations builds.

  • gh-149351: Avoid possible broken macOS framework install names when DESTDIR is specified during builds.

  • gh-149252: Update to WASI SDK 33.

  • gh-148690: Windows free-threaded builds now output to a different default path with default filenames, for example, PCbuild/amd64t/python.exe rather than PCbuild/amd64/python3.15t.exe. The PC/layout script has been updated to ensure compatibility of generated layouts.

  • gh-146475: Block Apple Clang from being used to build the JIT as it ships without required LLVM tools.

  • gh-148644: Errors during the PGO training job on Windows are no longer ignored, and a non-zero return code will cause the build to fail.

  • gh-148535: No longer use the gcc -fprofile-update=atomic flag on i686. The flag has been added to fix a random GCC internal error on PGO build (gh-145801) caused by corruption of profile data (.gcda files). The problem is that it makes the PGO build way slower (up to 47x slower) on i686. Since the GCC internal error was not seen on i686 so far, don’t use -fprofile-update=atomic on i686 anymore. Patch by Victor Stinner.

  • gh-148483: Use Py_GCC_ATTRIBUTE(unused) for stop_tracing label.

  • gh-148474: Fixed compilation of Python/pystrhex.c with older clang versions.

  • gh-146445: The Android build tools have been moved to the Platforms folder.

  • gh-146264: Fix static module builds on non-WASI targets by linking HACL dependencies as static libraries when MODULE_BUILDTYPE=static, preventing duplicate _Py_LibHacl_* symbol errors at link time.

  • gh-138451: Allow for custom LLVM path using LLVM_TOOLS_INSTALL_DIR during JIT build.

  • gh-133312: Add a new ./configure option --enable-static-libpython-for-interpreter which, when used with --enable-shared, continues to build the shared library but does not use it for the interpreter. Instead, libpython is statically linked into the interpreter, as if --enable-shared had not been used. This allows you to do a single build and get a Python interpreter binary that does not use a shared library but also get a shared library for use by other programs.

Windows

  • gh-149254: Updated bundled version of OpenSSL to 3.5.6.

  • gh-148690: Non-freethreaded builds on Windows now support extensions linked to python3t.dll, and will include a copy of that library in normal installs that references the non-freethreaded runtime.

  • gh-146458: Fix incorrect REPL height and width tracking on console window resize on Windows.

macOS

  • gh-142295: For Python macOS framework builds, update Info.plist files to be more compliant with current Apple guidelines. Original patch contributed by Martinus Verburg.

  • gh-149254: Atualiza o instalador do macOS para usar OpenSSL 3.5.6.

IDLE

  • gh-94523: Detect file if modified at local disk and prompt to ask refresh. Patch by Shixian Li.

  • gh-139551: Support rendering BaseExceptionGroup in IDLE.

  • gh-89520: Make IDLE extension configuration look at user config files, allowing user-installed extensions to have settings and key bindings defined in ~/.idlerc.

API C

Python 3.15.0 alpha 8

Release date: 2026-04-07

Segurança

Núcleo e embutidos

  • gh-148157: Fix an unlikely crash when parsing an invalid type comments for function parameters. Found by OSS Fuzz in #492782951.

  • gh-100239: Propagate result type and uniqueness information through _BINARY_OP_EXTEND in the tier 2 optimizer, enabling elimination of downstream type guards and selection of inplace float operations.

  • gh-148144: Initialize _PyInterpreterFrame.visited when copying interpreter frames so incremental GC does not read an uninitialized byte from generator and frame-object copies.

  • gh-148072: Cache pickle.dumps and pickle.loads per interpreter in the XIData framework, avoiding repeated module lookups on every cross-interpreter data transfer. This speeds up InterpreterPoolExecutor for mutable types (list, dict) by 1.7x–3.3x.

  • gh-148110: Fix sys.set_lazy_imports_filter() so relative lazy imports pass the resolved imported module name to the filter callback. Patch by Pablo Galindo.

  • gh-148083: Constant-fold _CONTAINS_OP_SET for frozenset. Patch by Donghee Na.

  • gh-144319: Fix a bug that could cause applications with specific allocation patterns to leak memory via Huge Pages if compiled with Huge Page support. Patch by Pablo Galindo

  • gh-147985: Make PySet_Contains() attempt a lock-free lookup, similar to set.__contains__(). This avoids acquiring the set object mutex in the normal case.

  • gh-147856: Allow the count argument of bytes.replace() to be a keyword.

  • gh-146615: Fix a crash in __get__() for METH_METHOD descriptors when an invalid (non-type) object is passed as the second argument. Patch by Steven Sun.

  • gh-146306: Optimize compact integer arithmetic in the JIT by mutating uniquely-referenced operands in place, avoiding allocation of a new int object. Speeds up the pyperformance spectral_norm benchmark by ~10%.

  • gh-146587: Fix type slot assignment incase of multiple slots for same name in type object implementation. Patch by Kumar Aditya.

  • gh-126910: Set frame pointers in aarch64-unknown-linux-gnu JIT code, allowing most native profilers and debuggers to unwind through them. Patch by Diego Russo

  • gh-146388: Adds a null check to handle when the JIT optimizer runs out of space when dealing with contradictions in make_bottom.

  • gh-146308: Fixed multiple error handling issues in the _remote_debugging module including a double-free in code object caching, memory leaks on allocation failure, missing exception checks in binary format varint decoding, reference leaks on error paths in frame chain processing, and inconsistent thread status error reporting across platforms. Patch by Pablo Galindo.

  • gh-146306: Optimize float arithmetic in the JIT by mutating uniquely-referenced operands in place, avoiding allocation of a new float object. Speeds up the pyperformance nbody benchmark by ~19%.

  • gh-146128: Fix a bug which could cause constant values to be partially corrupted in AArch64 JIT code. This issue is theoretical, and hasn’t actually been observed in unmodified Python interpreters.

  • gh-146250: Fixed a memory leak in SyntaxError when re-initializing it.

  • gh-146245: Fixed reference leaks in socket when audit hooks raise exceptions in socket.getaddrinfo() and socket.sendto().

  • gh-146151: memoryview now supports the float complex and double complex C types: formatting characters 'F' and 'D' respectively. Patch by Sergey B Kirpichev.

  • gh-146196: Fix potential Undefined Behavior in PyUnicodeWriter_WriteASCII() by adding a zero-length check. Patch by Shamil Abdulaev.

  • gh-146227: Fix wrong type in _Py_atomic_load_uint16 in the C11 atomics backend (pyatomic_std.h), which used a 32-bit atomic load instead of 16-bit. Found by Mohammed Zuhaib.

  • gh-146205: Fixed a bug where select.epoll.close(), select.kqueue.close(), and select.devpoll.close() silently ignored errors.

  • gh-146199: Comparison of code objects now handles errors correctly.

  • gh-145667: Remove the GET_ITER_YIELD_FROM instruction, modifying SEND to pair with GET_ITER when compiling yield from expressions.

  • gh-146192: Add Base32 support to binascii and improve the performance of the Base32 converters in base64. Patch by James Seo.

  • gh-135871: Improve multithreaded scaling of PyMutex in low-contention scenarios by reloading the lock’s internal state, without slowing down high-contention scenarios.

  • gh-146096: Fixed segmentation fault when called repr for BaseExceptionGroup with empty or 1-size tuple args.

  • gh-146056: Fix repr() for lists and tuples containing NULLs.

  • gh-145059: Fixed sys.lazy_modules to include lazy modules without submodules. Patch by Bartosz Sławecki.

  • gh-146041: Fix free-threading scaling bottleneck in sys.intern() and PyObject_SetAttr() by avoiding the interpreter-wide lock when the string is already interned and immortalized.

  • gh-145990: python --help-env sections are now sorted by environment variable name.

  • gh-145990: python --help-xoptions is now sorted by -X option name.

  • gh-145876: AttributeErrors and KeyErrors raised in keys() or __getitem__() during dictionary unpacking ({**mymapping} or func(**mymapping)) are no longer masked by TypeError.

  • gh-127958: Support tracing from function entrypoints in the JIT. Patch by Ken Jin.

  • gh-145376: Fix GC tracking in structseq.__replace__().

  • gh-145792: Fix out-of-bounds access when invoking faulthandler on a CPython build compiled without support for VLAs.

  • gh-142183: Avoid a pathological case where repeated calls at a specific stack depth could be significantly slower.

  • gh-145779: Improve scaling of classmethod() and staticmethod() calls in the free-threaded build by avoiding the descriptor __get__ call.

  • gh-145783: Fix an unlikely crash in the parser when certain errors were erroneously not propagated. Found by OSS Fuzz in #491369109.

  • gh-145685: Improve scaling of type attribute lookups in the free-threaded build by avoiding contention on the internal type lock.

  • gh-145713: Make bytearray.resize() thread-safe in the free-threaded build by using a critical section and calling the lock-held variant of the resize function.

  • gh-145036: In free-threaded build, fix race condition when calling __sizeof__() on a list

  • gh-134584: Eliminate redundant refcounting for MATCH_CLASS in the JIT.

  • gh-69605: Add math.integer to REPL auto-completion of imports.

  • gh-131798: Optimize _ITER_CHECK_RANGE and _ITER_CHECK_LIST in the JIT

  • gh-143414: Add tracking to the JIT optimizer to determine whether a reference is uniquely owned or shared

  • gh-143636: Fix a crash when calling SimpleNamespace.__replace__() on non-namespace instances. Patch by Bénédikt Tran.

  • gh-126910: Set frame pointers in x86_64-unknown-linux-gnu JIT code, allowing most native profilers and debuggers to unwind through them.

  • gh-140594: Fix an out of bounds read when a single NUL character is read from the standard input. Patch by Shamil Abdulaev.

  • gh-140870: Add support for module attributes in the REPL auto-completion of imports.

Biblioteca

Documentação

  • gh-126676: Expand argparse documentation for type=bool with a demonstration of the surprising behavior and pointers to common alternatives.

  • gh-145649: Fix text wrapping and formatting of -X option descriptions in the python(1) man page by using proper roff markup.

Testes

  • gh-144418: The Android testbed’s emulator RAM has been increased from 2 GB to 4 GB.

  • gh-146202: Fix a race condition in regrtest: make sure that the temporary directory is created in the worker process. Previously, temp_cwd() could fail on Windows if the “build” directory was not created. Patch by Victor Stinner.

Construção

  • gh-146541: The Android testbed can now be built for 32-bit ARM and x86 targets.

  • gh-146498: The iOS XCframework build script now ensures libpython isn’t included in installed app content, and is more robust in identifying standard library binary content that requires processing.

  • gh-146450: The Android build script was modified to improve parity with other platform build scripts.

  • gh-146446: The clean target for the Apple/iOS XCframework build script is now more selective when targeting a single architecture.

  • gh-146444: The Apple/iOS build script has been moved to the Platforms directory.

  • gh-146210: Fix building the jit stencils on Windows when the interpreter is built with a different clang version. Patch by Chris Eibl.

  • gh-145844: Update to WASI SDK 32.

  • gh-145801: When Python build is optimized with GCC using PGO, use -fprofile-update=atomic option to use atomic operations when updating profile information. This option reduces the risk of gcov Data Files (.gcda) corruption which can cause random GCC crashes. Patch by Victor Stinner.

  • gh-138850: Add --disable-epoll to configure

  • gh-145633: Remove support for ancient ARM platforms (ARMv4L and ARMv5L OABI boards), using mixed-endian representation for doubles. Patch by Sergey B Kirpichev.

  • gh-85277: Fix building without stropts.h or empty stropts.h

Windows

  • gh-140131: Fix REPL cursor position on Windows when module completion suggestion line hits console width.

macOS

Ferramentas/Demos

  • gh-135953: Properly identify the main thread in the Gecko profiler collector by using a status flag from the interpreter state instead of relying on threading.main_thread() in the collector process.

  • gh-145976: Remove Misc/indent.pro, a configuration file for GNU indent(1).

  • gh-145976: Remove Misc/vgrindefs and Misc/Porting.

API C

Python 3.15.0 alpha 7

Release date: 2026-03-10

Windows

Testes

  • gh-144741: Fix test_frame_pointer_unwind when Python is built with --enable-shared. Classify also libpython frames as "python". Patch by Victor Stinner.

  • gh-144739: When Python was compiled with system expat older then 2.7.2 but tests run with newer expat, still skip test.test_pyexpat.MemoryProtectionTest.

Segurança

Biblioteca

Documentação

Núcleo e embutidos

  • gh-145701: Fix SystemError when __classdict__ or __conditional_annotations__ is in a class-scope inlined comprehension. Found by OSS Fuzz in #491105000.

  • gh-145615: Fixed a memory leak in the free-threaded build where mimalloc pages could become permanently unreclaimable until the owning thread exited.

  • gh-116738: Make mmap.mmap.set_name() thread-safe on the free threaded build.

  • gh-145566: In the free threading build, skip the stop-the-world pause when reassigning __class__ on a newly created object.

  • gh-143055: Fix crash in AST unparser when unparsing dict comprehension unpacking. Found by OSS Fuzz in #489790200.

  • gh-145335: Fix a crash in os.pathconf() when called with -1 as the path argument.

  • gh-145376: Fix reference leaks in various unusual error scenarios.

  • gh-145234: Fixed a SystemError in the parser when an encoding cookie (for example, UTF-7) decodes to carriage returns (\r). Newlines are now normalized after decoding in the string tokenizer.

    Patch by Pablo Galindo.

  • gh-145275: Added the -X pathconfig_warnings and PYTHON_PATHCONFIG_WARNINGS options, allowing to disable warnings from A inicialização do caminho de pesquisa de módulos sys.path.

  • gh-145273: A warning is now shown during A inicialização do caminho de pesquisa de módulos sys.path if it can’t find a valid standard library.

  • gh-145241: Specialized the parser error for when with items are followed by a trailing comma (for example, with item,:), raising a clearer SyntaxError message. Patch by Pablo Galindo and Bartosz Sławecki.

  • gh-130555: Fix use-after-free in dict.clear() when the dictionary values are embedded in an object and a destructor causes re-entrant mutation of the dictionary.

  • gh-145197: Fix JIT trace crash when recording function from cleared generator frame.

  • gh-145187: Fix compiler assertion fail when a type parameter bound contains an invalid expression in a conditional block.

  • gh-145142: Fix a crash in the free-threaded build when the dictionary argument to str.maketrans() is concurrently modified.

  • gh-145118: str.maketrans() now accepts frozendict.

  • gh-144015: Speed up bytes.hex(), bytearray.hex(), binascii.hexlify(), and hashlib .hexdigest() operations with SIMD on x86-64, ARM64, and ARM32 with NEON when built with gcc (version 12 or higher) or clang (version 3 or higher) compilers. Around 1.1-3x faster for common 16-64 byte inputs such as hashlib hex digests, and up to 8x faster for larger data.

  • gh-145118: type() now accepts frozendict as an argument.

  • gh-145064: Fix JIT optimizer assertion failure during CALL_ALLOC_AND_ENTER_INIT side exit.

  • gh-145055: exec() and eval() now accept frozendict for globals. Patch by Victor Stinner.

  • gh-145058: Fix a crash when __lazy_import__() is passed a non-string argument, by raising an TypeError instead.

  • gh-144995: Optimize memoryview comparison: a memoryview is equal to itself, there is no need to compare values. Patch by Victor Stinner.

  • gh-141510: Update specializer to support frozendict. Patch by Donghee Na.

  • gh-141510: Optimize frozendict.fromkeys() to avoid unnecessary thread-safety operations in frozendict cases. Patch by Donghee Na.

  • gh-100239: Speedup BINARY_OP_EXTEND for exact floats and medium-size integers by up to 15%. Patch by Chris Eibl.

  • gh-144914: Use mimalloc for raw memory allocations such as via PyMem_RawMalloc() for better performance on free-threaded builds. Patch by Kumar Aditya.

  • gh-144872: Fix heap buffer overflow in the parser found by OSS-Fuzz.

  • gh-144766: Fix a crash in fork child process when perf support is enabled.

  • gh-144759: Fix undefined behavior in the lexer when start and multi_line_start pointers are NULL in _PyLexer_remember_fstring_buffers() and _PyLexer_restore_fstring_buffers(). The NULL pointer arithmetic (NULL - valid_pointer) is now guarded with explicit NULL checks.

  • gh-141510: Add built-in frozendict type. Patch by Victor Stinner.

  • gh-144681: Fix a JIT assertion failure when a conditional branch jumps to the same target as the fallthrough path.

  • gh-143300: Add PyUnstable_SetImmortal() C-API function to mark objects as immortal.

  • gh-144702: Clarify the error message raised when a class pattern is used to match on a non-class object.

  • gh-144569: Optimize BINARY_SLICE for list, tuple, and unicode by avoiding temporary slice object creation.

  • gh-144438: Align the QSBR thread state array to a 64-byte cache line boundary to avoid false sharing in the free-threaded build.

  • gh-142349: Implement PEP 810. Patch by Pablo Galindo and Dino Viehland.

  • gh-141226: Deprecate PEP 456 support for providing an external definition of the string hashing scheme. Removal is scheduled for Python 3.19. Patch by Bénédikt Tran.

  • gh-138912: Improve MATCH_CLASS performance by up to 52% in certain cases. Patch by Marc Mueller.

  • gh-130327: Fix erroneous clearing of an object’s __dict__ if overwritten at runtime.

  • gh-80667: Literals using the \N{name} escape syntax can now construct CJK ideographs and Hangul syllables using case-insensitive names.

API C

Construção

  • gh-144533: Use wasmtime’s --argv0 to auto-discover sysconfig in WASI builds

  • gh-145110: Fix targets “Clean” and “CLeanAll” in case of PGO builds on Windows. Patch by Chris Eibl.

  • gh-144679: When building with Visual Studio 2026 (Version 18), use PlatformToolSet v145 by default. Patch by Chris Eibl.

  • gh-144675: Update to WASI SDK 30.

  • gh-136677: Introduce executable specific linker flags to ./configure.

Python 3.15.0 alpha 6

Release date: 2026-02-11

macOS

  • gh-144648: Allowed _remote_debugging to build on more OS versions by using proc_listpids() rather than proc_listallpids().

  • gh-124111: Update macOS installer to use Tcl/Tk 9.0.3.

  • gh-144551: Atualiza o instalador do macOS para usar OpenSSL 3.5.5.

Windows

Testes

  • gh-144415: The Android testbed now distinguishes between stdout/stderr messages which were triggered by a newline, and those triggered by a manual call to flush. This fixes logging of progress indicators and similar content.

  • gh-65784: Add support for parametrized resource wantobjects in regrtests, which allows to run Tkinter tests with the specified value of tkinter.wantobjects, for example -u wantobjects=0.

Segurança

  • gh-144125: BytesGenerator will now refuse to serialize (write) headers that are unsafely folded or delimited; see verify_generated_headers. (Contributed by Bas Bloemsaat and Petr Viktorin in gh-121650).

  • gh-143935: Fixed a bug in the folding of comments when flattening an email message using a modern email policy. Comments consisting of a very long sequence of non-foldable characters could trigger a forced line wrap that omitted the required leading space on the continuation line, causing the remainder of the comment to be interpreted as a new header field. This enabled header injection with carefully crafted inputs.

  • gh-143925: Reject control characters in data: URL media types.

  • gh-143923: Reject control characters in POP3 commands.

  • gh-143921: Reject control characters in IMAP commands.

  • gh-143919: Reject control characters in http.cookies.Morsel fields and values.

  • gh-143916: Reject C0 control characters within wsgiref.headers.Headers fields, values, and parameters.

Biblioteca

IDLE

  • gh-143774: Better explain the operation of Format / Format Paragraph.

Núcleo e embutidos

  • gh-134584: Optimize and eliminate ref-counting in _BINARY_OP_SUBSCR_LIST_SLICE

  • gh-144563: Fix interaction of the Tachyon profiler and ctypes and other modules that load the Python shared library (if present) in an independent map as this was causing the mechanism that loads the binary information to be confused. Patch by Pablo Galindo

  • gh-144601: Fix crash when importing a module whose PyInit function raises an exception from a subinterpreter.

  • gh-144549: Fix building the tail calling interpreter on Visual Studio 2026 with free-threading.

  • gh-144513: Fix potential deadlock when using critical sections during stop-the-world pauses in the free-threaded build.

  • gh-131798: Optimise _GUARD_TOS_SLICE in the JIT.

  • gh-144330: Move classmethod and staticmethod initialization from __init__() to __new__(). Patch by Victor Stinner.

  • gh-144446: Fix data races in the free-threaded build when reading frame object attributes while another thread is executing the frame.

  • gh-120321: Add gi_state, cr_state, and ag_state attributes to generators, coroutines, and async generators that return the current state as a string (e.g., GEN_RUNNING). The inspect module functions getgeneratorstate(), getcoroutinestate(), and getasyncgenstate() now return these attributes directly.

  • gh-141563: Fix thread safety of PyDateTime_IMPORT.

  • gh-144280: Fix a bug in JIT where the predicate symbol had no truthiness

  • gh-140550: In PyModuleDef.m_slots, allow slots that repeat information present in PyModuleDef.

  • gh-139103: Improve scaling of namedtuple() instantiation in the free-threaded build.

  • gh-144307: Prevent a reference leak in module teardown at interpreter finalization.

  • gh-144319: Add huge pages support for the pymalloc allocator. Patch by Pablo Galindo

  • gh-120321: Made gi_yieldfrom thread-safe in the free-threading build by using a lightweight lock on the frame state.

  • gh-144194: Fix error handling in perf jitdump initialization on memory allocation failure.

  • gh-143962: Name suggestion for not normalized name suggests now the normalized name or the closest name to the normalized name. If the suggested name is not ASCII, include also its ASCII representation.

  • gh-144157: bytes.translate() now allows the compiler to unroll its loop more usefully for a 2x speedup in the common no-deletions specified case.

  • gh-144068: Fix JIT tracer memory leak, ensure the JIT tracer state is freed when daemon threads are cleaned up during interpreter shutdown.

  • gh-144012: Check if the result is NULL in BINARY_OP_EXTENT opcode.

  • gh-144007: Eliminate redundant refcounting in the JIT for BINARY_OP.

  • gh-144005: Eliminate redundant refcounting from BINARY_OP_EXTEND.

  • gh-143939: Fix erroneous “cannot reuse already awaited coroutine” error that could occur when a generator was run during the process of clearing a coroutine’s frame.

  • gh-141805: Fix crash in set when objects with the same hash are concurrently added to the set after removing an element with the same hash while the set still contains elements with the same hash.

  • gh-143670: Fixes a crash in ga_repr_items_list function.

  • gh-143650: Fix race condition in importlib where a thread could receive a stale module reference when another thread’s import fails.

  • gh-143569: Generator expressions in 3.15 now conform to the documented behavior when the iterable does not support iteration. This matches the behavior in 3.14 and earlier

  • gh-143192: Improve performance of bitwise operations on multi-digit ints.

  • gh-132657: If we are specializing to LOAD_GLOBAL_MODULE or LOAD_ATTR_MODULE, try to enable deferred reference counting for the value, if the object is owned by a different thread. This applies to the free-threaded build only and should improve scaling of multi-threaded programs. Note that when deferred reference counting is enabled, the object will be deallocated by the GC, rather than by Py_DECREF().

  • gh-143055: Implement PEP 798 (Unpacking in Comprehensions). Patch by Adam Hartz.

  • gh-142037: Improve error messages for printf-style formatting. For errors in the format string, always include the position of the start of the format unit. For errors related to the formatted arguments, always include the number or the name of the argument. Raise more specific errors and include more information (type and number of arguments, most probable causes of error).

  • gh-140557: bytearray buffers now have the same alignment when empty as when allocated. Unaligned buffers can still be created by slicing.

  • gh-140232: Frozenset objects with immutable elements are no longer tracked by the garbage collector.

  • gh-115231: Setup __module__ attribute for built-in static methods. Patch by Sergey B Kirpichev.

API C

Construção

  • gh-140421: Disable the perf trampoline on older macOS versions where it cannot be built.

  • gh-144309: Build Python with POSIX 2024, instead of POSIX 2008. Patch by Victor Stinner.

  • gh-144278: Enables defining the _PY_IMPL_NAME and _PY_IMPL_CACHE_TAG preprocessor definitions to override sys.implementation at build time. Definitions need to include quotes when setting to a string literal. Setting the cache tag to NULL has the effect of completely disabling automatic creation and use of .pyc files.

  • gh-143960: Add support for OpenSSL 3.6, drop EOL 3.2. Patch by Hugo van Kemenade.

  • gh-143941: Move WASI-related files to Platforms/WASI. Along the way, leave a deprecated Tools/wasm/wasi/__main__.py behind for backwards-compatibility.

  • gh-143842: Prevent static builds from clashing with curses by making the optimizer COLORS table static.

Python 3.15.0 alpha 5

Release date: 2026-01-14

Windows

  • gh-143082: Fix pdb arrow key history not working when stdin is sys.stdin.

  • gh-128067: Fix a bug in PyREPL on Windows where output without a trailing newline was overwritten by the next prompt.

Ferramentas/Demos

  • gh-142095: Make gdb ‘py-bt’ command use frame from thread local state when available. Patch by Sam Gross and Victor Stinner.

Testes

  • gh-143460: Skip tests relying on infinite recusion if stack size is unlimited.

  • gh-143553: Add support for parametrized resources, such as -u xpickle=2.7.

  • bpo-31391: Forward-port test_xpickle from Python 2 to Python 3 and add the resource back to test’s command line.

Biblioteca

  • gh-143706: Fix multiprocessing forkserver so that sys.argv is correctly set before __main__ is preloaded. Previously, sys.argv was empty during main module import in forkserver child processes. This fixes a regression introduced in 3.13.8 and 3.14.1. Root caused by Aaron Wieczorek, test provided by Thomas Watson, thanks!

  • gh-143638: Forbid reentrant calls of the pickle.Pickler and pickle.Unpickler methods for the C implementation. Previously, this could cause crash or data corruption, now concurrent calls of methods of the same object raise RuntimeError.

  • gh-143658: importlib.metadata: Use str.translate() to improve performance of importlib.metadata.Prepared.normalize(). Patch by Hugo van Kemenade and Henry Schreiner.

  • gh-78724: Raise RuntimeError’s when user attempts to call methods on half-initialized Struct objects, For example, created by Struct.__new__(Struct). Patch by Sergey B Kirpichev.

  • gh-143196: Fix crash when the internal encoder object returned by undocumented function json.encoder.c_make_encoder() was called with non-zero second (_current_indent_level) argument.

  • gh-143191: _thread.stack_size() now raises ValueError if the stack size is too small. Patch by Victor Stinner.

  • gh-143547: Fix sys.unraisablehook() when the hook raises an exception and changes sys.unraisablehook(): hold a strong reference to the old hook. Patch by Victor Stinner.

  • gh-139686: Revert 0a97941245f1dda6d838f9aaf0512104e5253929 and 57db12514ac686f0a752ec8fe1c08b6daa0c6219 which made importlib.reload a no-op for lazy modules; caused Buildbot failures.

  • gh-143517: annotationlib.get_annotations() no longer raises a SyntaxError when evaluating a stringified starred annotation that starts with one or more whitespace characters followed by a *. Patch by Bartosz Sławecki.

  • gh-143474: Add os.RWF_ATOMIC constant for Linux 6.11+.

  • gh-143445: Speed up copy.deepcopy() by 1.04x.

  • gh-143378: Fix use-after-free crashes when a BytesIO object is concurrently mutated during write() or writelines().

  • gh-143368: Fix endless retry loop in profiling.sampling blocking mode when threads cannot be seized due to EPERM. Such threads are now skipped instead of causing repeated error messages. Patch by Pablo Galindo.

  • gh-143346: Fix incorrect wrapping of the Base64 data in plistlib._PlistWriter when the indent contains a mix of tabs and spaces.

  • gh-140025: queue: Fix SimpleQueue.__sizeof__() computation.

  • gh-143310: tkinter: fix a crash when a Python list is mutated during the conversion to a Tcl object (e.g., when setting a Tcl variable). Patch by Bénédikt Tran.

  • gh-143309: Fix a crash in os.execve() on non-Windows platforms when given a custom environment mapping which is then mutated during parsing. Patch by Bénédikt Tran.

  • gh-143308: pickle: fix use-after-free crashes when a PickleBuffer is concurrently mutated by a custom buffer callback during pickling. Patch by Bénédikt Tran and Aaron Wieczorek.

  • gh-142939: Performance optimisations for difflib.get_close_matches()

  • gh-124951: The base64 implementation behind the binascii, base64, and related codec has been optimized for modern pipelined CPU architectures and now performs 2-3x faster across all platforms.

  • gh-143237: Fix support of named pipes in the rotating logging handlers.

  • gh-143249: Fix possible buffer leaks in Windows overlapped I/O on error handling.

  • gh-143241: zoneinfo: fix infinite loop in ZoneInfo.from_file when parsing a malformed TZif file. Patch by Fatih Celik.

  • gh-142830: sqlite3: fix use-after-free crashes when the connection’s callbacks are mutated during a callback execution. Patch by Bénédikt Tran.

  • gh-143200: xml.etree.ElementTree: fix use-after-free crashes in __getitem__() and __setitem__() methods of Element when the element is concurrently mutated. Patch by Bénédikt Tran.

  • gh-143214: Add the wrapcol parameter in binascii.b2a_base64() and base64.b64encode().

  • gh-142195: Updated timeout evaluation logic in subprocess to be compatible with deterministic environments like Shadow where time moves exactly as requested.

  • gh-140739: Fix several crashes due to reading invalid memory in the new Tachyon sampling profiler. Patch by Pablo Galindo.

  • gh-142164: Fix the ctypes bitfield overflow error message to report the correct offset and size calculation.

  • gh-143145: Fixed a possible reference leak in ctypes when constructing results with multiple output parameters on error.

  • gh-143103: Add padding support to base64.z85encode() via the pad parameter.

  • gh-130796: Undeprecate the locale.getdefaultlocale() function. Patch by Victor Stinner.

  • gh-74902: Add the iter_graphemes() function in the unicodedata module to iterate over grapheme clusters according to rules defined in Unicode Standard Annex #29, “Unicode Text Segmentation”. Add grapheme_cluster_break(), indic_conjunct_break() and extended_pictographic() functions to get the properties of the character which are related to the above algorithm.

  • gh-143004: Fix a potential use-after-free in collections.Counter.update() when user code mutates the Counter during an update.

  • gh-140648: The asyncio REPL now respects the -I flag (isolated mode). Previously, it would load and execute PYTHONSTARTUP even if the flag was set. Contributed by Bartosz Sławecki.

  • gh-142991: Fixed socket operations such as recvfrom() and sendto() for FreeBSD divert(4) socket.

  • gh-116738: Make the attributes in lzma thread-safe on the free threaded build.

  • gh-142950: Fix regression in argparse where format specifiers in help strings raised ValueError.

  • gh-142881: Fix concurrent and reentrant call of atexit.unregister().

  • gh-142615: Fix possible crashes when initializing asyncio.Task or asyncio.Future multiple times. These classes can now be initialized only once and any subsequent initialization attempt will raise a RuntimeError. Patch by Kumar Aditya.

  • gh-142517: The non-compat32 email policies now correctly handle refolding encoded words that contain bytes that can not be decoded in their specified character set. Previously this resulted in an encoding exception during folding.

  • gh-138122: The Tachyon profiler’s live TUI now integrates with the experimental _colorize theming system. Users can customize colors via _colorize.set_theme() (experimental API, subject to change). A LiveProfilerLight theme is provided for light terminal backgrounds. Patch by Pablo Galindo.

  • gh-142306: Improve errors for Element.remove.

  • gh-63016: Add a flags parameter to mmap.mmap.flush() to control synchronization behavior.

  • gh-139262: Some keystrokes can be swallowed in the new PyREPL on Windows, especially when used together with the ALT key. Fix by Chris Eibl.

  • gh-138897: Improved license/copyright/credits display in the REPL: now uses a pager.

  • gh-135852: Add _winapi.RegisterEventSource(), _winapi.DeregisterEventSource() and _winapi.ReportEvent(). Using these functions in NTEventLogHandler to replace pywin32.

  • gh-109263: Starting a process from spawn context in multiprocessing no longer sets the start method globally.

  • gh-132715: Skip writing objects during marshalling once a failure has occurred.

Documentação

Núcleo e embutidos

  • gh-134584: Eliminate redundant refcounting from _CONTAINS_OP, _CONTAINS_OP_SET and _CONTAINS_OP_DICT.

  • gh-143604: Fix a reference counting issue in the JIT tracer where the current executor could be prematurely freed during tracing.

  • gh-143469: Enable LOAD_ATTR_MODULE specialization even if __getattr__() is defined in module.

  • gh-134584: Eliminate redundant refcounting from TO_BOOL_STR.

  • gh-143377: Fix a crash in _interpreters.capture_exception() when the exception is incorrectly formatted. Patch by Bénédikt Tran.

  • gh-139757: Add BINARY_OP_SUBSCR_USTR_INT to specialize reading an ASCII character from any string. Patch by Chris Eibl.

  • gh-141504: Factor out tracing and optimization heuristics into a single object. Patch by Donghee Na.

  • gh-142982: Specialize CALL_FUNCTION_EX for Python and non-Python callables.

  • gh-136924: The interactive help mode in the REPL no longer incorrectly syntax highlights text input as Python code. Contributed by Olga Matoula.

  • gh-139757: Fix unintended bytecode specialization for non-ascii string. Patch by Donghee Na, Ken Jin and Chris Eibl.

  • gh-143361: Add PY_VECTORCALL_ARGUMENTS_OFFSET to _Py_CallBuiltinClass_StackRefSteal to avoid redundant allocations

  • gh-131798: The JIT optimizer now understands more generator instructions.

  • gh-134584: Eliminate redundant refcounting from _LOAD_ATTR_SLOT.

  • gh-143189: Fix crash when inserting a non-str key into a split table dictionary when the key matches an existing key in the split table but has no corresponding value in the dict.

  • gh-143228: Fix use-after-free in perf trampoline when toggling profiling while threads are running or during interpreter finalization with daemon threads active. The fix uses reference counting to ensure trampolines are not freed while any code object could still reference them. Pach by Pablo Galindo

  • gh-142664: Fix a use-after-free crash in memoryview.__hash__ when the __hash__ method of the referenced object mutates that object or the view. Patch by Bénédikt Tran.

  • gh-142557: Fix a use-after-free crash in bytearray.__mod__ when the bytearray is mutated while formatting the %-style arguments. Patch by Bénédikt Tran.

  • gh-143195: Fix use-after-free crashes in bytearray.hex() and memoryview.hex() when the separator’s __len__() mutates the original object. Patch by Bénédikt Tran.

  • gh-143183: Fix a bug in the JIT when dealing with unsupported control-flow or operations.

  • gh-142975: Fix crash after unfreezing all objects tracked by the garbage collector on the free threaded build.

  • gh-143135: Set sys.flags.inspect to 1 when PYTHONINSPECT is 0. Previously, it was set to 0 in this case.

  • gh-143123: Protect the JIT against recursive tracing.

  • gh-143092: Fix a crash in the JIT when dealing with list.append(x) style code.

  • gh-143003: Fix an overflow of the shared empty buffer in bytearray.extend() when __length_hint__() returns 0 for non-empty iterator.

  • gh-143006: Fix a possible assertion error when comparing negative non-integer float and int with the same number of bits in the integer part.

  • gh-116738: Fix thread safety of contextvars.Context.run().

  • gh-142829: Fix a use-after-free crash in contextvars.Context comparison when a custom __eq__ method modifies the context via set().

  • gh-142863: Generate optimized bytecode when calling list or set with generator expression.

  • gh-41779: Allowed defining any __slots__ for a class derived from tuple (including classes created by collections.namedtuple()).

  • gh-69605: Fix edge-cases around already imported modules in the REPL auto-completion of imports.

  • gh-138568: Adjusted the built-in help() function so that empty inputs are ignored in interactive mode.

  • gh-131798: Remove bounds check when indexing into tuples with a constant index.

  • gh-134584: Eliminate redundant refcounting from _CALL_TYPE_1. Patch by Tomas Roun

  • gh-132108: Speed up int.from_bytes() when passed object supports buffer protocol, like bytearray by ~1.2x.

  • gh-128334: Make the slice class subscriptable at runtime to be consistent with typing implementation.

API C

Python 3.15.0 alpha 4

Release date: 2026-01-13

Testes

  • gh-142836: Accommodated Solaris in test_pdb.test_script_target_anonymous_pipe.

Biblioteca

  • gh-122431: Corrected the error message in readline.append_history_file() to state that nelements must be non-negative instead of positive.

  • gh-143046: The asyncio REPL no longer prints copyright and version messages in the quiet mode (-q). Patch by Bartosz Sławecki.

  • gh-80744: Fix issue where pdb would read a .pdbrc twice if launched from the home directory

  • gh-138122: Add blocking mode to Tachyon for accurate stack traces in applications with many generators or fast-changing call stacks. Patch by Pablo Galindo.

  • gh-143010: Fixed a bug in mailbox where the precise timing of an external event could result in the library opening an existing file instead of a file it expected to create.

  • gh-112127: Fix possible use-after-free in atexit.unregister() when the callback is unregistered during comparison.

  • gh-138122: Fix incomplete stack traces in the Tachyon profiler’s frame cache when profiling code with deeply nested generators. The frame cache now validates that stack traces reach the base frame before caching, preventing broken flamegraphs. Patch by Pablo Galindo.

  • gh-142834: Change the pdb commands command to use the last available breakpoint instead of failing when the most recently created breakpoint was deleted.

  • gh-142783: Fix zoneinfo use-after-free with descriptor _weak_cache. a descriptor as _weak_cache could cause crashes during object creation. The fix ensures proper reference counting for descriptor-provided objects.

  • gh-76007: Deprecate VERSION from xml.etree.ElementTree and version from xml.sax.expatreader and xml.sax.handler. Patch by Hugo van Kemenade.

  • gh-142784: The asyncio REPL now properly closes the loop upon the end of interactive session. Previously, it could cause surprising warnings. Contributed by Bartosz Sławecki.

  • gh-138122: Add binary output format to profiling.sampling for compact storage of profiling data. The new --binary option captures samples to a file that can be converted to other formats using the replay command. Patch by Pablo Galindo

  • gh-142495: collections.defaultdict now prioritizes __setitem__() when inserting default values from default_factory. This prevents race conditions where a default value would overwrite a value set before default_factory returns.

  • gh-142654: Show the clearer error message when using profiling.sampling on an unknown PID.

  • gh-142560: Fix use-after-free in bytearray search-like methods (find(), count(), index(), rindex(), and rfind()) by marking the storage as exported which causes reallocation attempts to raise BufferError. For contains(), split(), and rsplit() the buffer protocol is used for this.

  • gh-142419: mmap.mmap.set_name() method added to annotate an anonymous memory map if Linux kernel supports PR_SET_VMA_ANON_NAME (Linux 5.17 or newer). Patch by Donghee Na.

  • gh-139971: pydoc: Ensure that the link to the online documentation of a stdlib module is correct.

  • gh-124098: Fix issue where methods in handlers that lacked the protocol name but matched a valid base handler method (e.g., _open() or error()) were incorrectly added to urllib.request.OpenerDirector’s handlers. Contributed by Andrea Mattei.

  • gh-136282: Add support for UNNAMED_SECTION when creating a section via the mapping protocol access

Núcleo e embutidos

  • gh-143057: Avoid locking in PyTraceMalloc_Track() and PyTraceMalloc_Untrack() when tracemalloc is not enabled.

  • gh-139109: Add missing terminator in certain cases when tracing in the new JIT compiler.

  • gh-142961: Fix a segfault in the JIT when constant folding len(tuple).

  • gh-142776: Fix a file descriptor leak in import.c

  • gh-139757: Fix building JIT stencils on free-threaded builds.

  • gh-129068: Make concurrent iteration over the same range iterator thread-safe in the free threading build.

  • gh-142543: Fix a stack overflow on Clang JIT build configurations with full LTO.

  • gh-142448: Fix a bug when using monitoring with the JIT.

  • gh-142766: Clear the frame of a generator when generator.close() is called.

  • gh-134584: Eliminate redundant refcounting from _LOAD_ATTR_INSTANCE_VALUE.

  • gh-134584: Eliminate redundant refcounting from _STORE_ATTR_WITH_HINT.

  • gh-142476: Fix a memory leak in the experimental Tier 2 optimizer when creating executors. Patched by Shamil Abdulaev.

  • gh-100964: Fix reference cycle in exhausted generator frames. Patch by Savannah Ostrowski.

  • gh-139922: Allow building CPython with the tail calling interpreter on Visual Studio 2026 MSVC. This provides a performance gain over the prior interpreter for MSVC. Patch by Ken Jin, Brandt Bucher, and Chris Eibl. With help from the MSVC team including Hulon Jenkins.

Python 3.15.0 alpha 3

Release date: 2025-12-16

Ferramentas/Demos

  • gh-141692: Cada componente de um XCframework para iOS agora contém uma pasta lib que contém um link simbólico para a biblioteca dinâmica libpython. Isso permite que módulos binários sejam compilados para iOS usando vinculação dinâmica de bibliotecas, em vez de vinculação de framework.

Testes

  • gh-140381: Fix flaky test_profiling tests on i686 and s390x architectures by increasing slow_fibonacci call frequency from every 5th iteration to every 2nd iteration.

  • gh-140210: Make test_sysconfig.test_parse_makefile_renamed_vars less fragile by clearing the environment variables before parsing the Makefile.

Segurança

  • gh-142145: Remove quadratic behavior in xml.minidom node ID cache clearing.

  • gh-42400: Fix buffer overflow in _Py_wrealpath() for paths exceeding MAXPATHLEN bytes by using dynamic memory allocation instead of fixed-size buffer. Patch by Shamil Abdulaev.

  • gh-119451: Fix a potential memory denial of service in the http.client module. When connecting to a malicious server, it could cause an arbitrary amount of memory to be allocated. This could have led to symptoms including a MemoryError, swapping, out of memory (OOM) killed processes or containers, or even system crashes.

  • gh-119342: Fix a potential memory denial of service in the plistlib module. When reading a Plist file received from untrusted source, it could cause an arbitrary amount of memory to be allocated. This could have led to symptoms including a MemoryError, swapping, out of memory (OOM) killed processes or containers, or even system crashes.

Biblioteca

  • gh-142754: Add the ownerDocument attribute to xml.dom.minidom elements and attributes created by directly instantiating the Element or Attr class. Note that this way of creating nodes is not supported; creator functions like xml.dom.Document.documentElement() should be used instead.

  • gh-142594: Fix crash in TextIOWrapper.close() when the underlying buffer’s closed property calls detach().

  • gh-76007: Deprecate __version__ from ctypes. Patch by Hugo van Kemenade.

  • gh-76007: Deprecate __version__ from wsgiref.simple_server. Patch by Hugo van Kemenade.

  • gh-142651: unittest.mock: fix a thread safety issue where Mock.call_count may return inaccurate values when the mock is called concurrently from multiple threads.

  • gh-76007: Deprecate __version__ from http.server. Patch by Hugo van Kemenade.

  • gh-138122: Add --subprocesses flag to profiling.sampling CLI to automatically profile subprocesses spawned by the target. When enabled, the profiler monitors for new Python subprocesses and profiles each one separately, writing results to individual output files. This is useful for profiling applications that use multiprocessing, ProcessPoolExecutor, or other subprocess-based parallelism. Patch by Pablo Galindo.

  • gh-142595: Added type check during initialization of the decimal module to prevent a crash in case of broken stdlib. Patch by Sergey B Kirpichev.

  • gh-142556: Fix crash when a task gets re-registered during finalization in asyncio. Patch by Kumar Aditya.

  • gh-138122: Add --mode=exception to the sampling profiler to capture samples only from threads with an active exception, useful for analyzing exception handling overhead. Patch by Pablo Galindo.

  • gh-142539: traceback: Fix location of carets in SyntaxErrors when the source contains wide characters.

  • gh-123241: Avoid reference count operations in garbage collection of ctypes objects.

  • gh-142451: hmac: correctly copy HMAC attributes for objects copied through HMAC.copy(). Patch by Bénédikt Tran.

  • gh-138122: The profiling.sampling flamegraph profiler now supports inverted flamegraph view that aggregates all leaf nodes. In a standard flamegraph, if a hot function is called from multiple locations, it appears multiple times as separate leaf nodes. In the inverted flamegraph, all occurrences of the same leaf function are merged into a single aggregated node at the root, showing the total hotness of that function in one place. The children of each aggregated node represent its callers, making it easier to identify which functions consume the most CPU time and where they are called from.

  • gh-112527: The help text for required options in argparse no longer extended with “ (default: None)”.

  • gh-142438: Fixed a possible leaked GIL in _PySSL_keylog_callback.

  • gh-138122: Add bytecode-level instruction profiling to the sampling profiler via the new --opcodes flag. When enabled, the profiler captures which bytecode opcode is executing at each sample, including Python 3.11+ adaptive specializations, and visualizes this data in the heatmap, flamegraph, gecko, and live output formats. Patch by Pablo Galindo

  • gh-142389: Add backtick markup support in argparse description and epilog text to highlight inline code when color output is enabled.

  • gh-142346: Corrige a formatação de uso para grupos mutuamente exclusivos em argparse quando eles são precedidos por argumentos posicionais ou seguidos ou misturados com outros argumentos opcionais.

  • gh-142374: Fix cumulative percentage calculation for recursive functions in the new sampling profiler. When profiling recursive functions, cumulative statistics (cumul%, cumtime) could exceed 100% because each recursive frame in a stack was counted separately. For example, a function recursing 500 times in every sample would show 50000% cumulative presence. The fix deduplicates locations within each sample so cumulative stats correctly represent “percentage of samples where this function was on the stack”. Patch by Pablo Galindo.

  • gh-142315: Pdb can now run scripts from anonymous pipes used in process substitution. Patch by Bartosz Sławecki.

  • gh-64532: Subparser help now includes required optional arguments from the parent parser in the usage, making it clearer what arguments are needed to run a subcommand. Patch by Savannah Ostrowski.

  • gh-142207: Fix: profiling.sampling may cause assertion !(has_gil && gil_requested)

  • gh-142332: Corrige formatação de uso para argumentos posicionais em grupos mutuamente exclusivos em argparse. em argparse.

  • gh-142282: Fix winreg.QueryValueEx() to not accidentally read garbage buffer under race condition.

  • gh-142318: Fix typing 'q' at the help of the interactive tachyon profiler exiting the profiler.

  • gh-75949: Corrige o argparse para preservar os separadores | em grupos mutuamente exclusivos quando a linha de uso quebra devido ao comprimento.

  • gh-142267: Melhora o desempenho do argparse armazenando em cache o formatador usado para validação de argumentos.

  • gh-139862: Remove color parameter from argparse.HelpFormatter constructor. Color is controlled by ArgumentParser.

  • gh-68552: Os defeitos MisplacedEnvelopeHeaderDefect e Missing header name agora são passados corretamente para o método handle_defect de policy em FeedParser.

  • gh-142206: The resource tracker in the multiprocessing module can now understand messages from older versions of itself. This avoids issues with upgrading Python while it is running. (Note that such ‘in-place’ upgrades are not tested.)

  • gh-142214: Fix two regressions in dataclasses in Python 3.14.1 related to annotations.

    • An exception is no longer raised if slots=True is used and the __init__ method does not have an __annotate__ attribute (likely because init=False was used).

    • An exception is no longer raised if annotations are requested on the __init__ method and one of the fields is not present in the class annotations. This can occur in certain dynamic scenarios.

    Patch by Jelle Zijlstra.

  • gh-142203: Remove the debug_override parameter from importlib.util.cache_from_source() which has been deprecated since Python 3.5.

  • gh-138122: The _remote_debugging module now implements frame caching in the RemoteUnwinder class to reduce memory reads when profiling remote processes. When cache_frames=True, unchanged portions of the call stack are reused from previous samples, significantly improving profiling performance for deep call stacks.

  • gh-116738: Fix cmath data race when initializing trigonometric tables with subinterpreters.

  • gh-141982: Allow pdb to set breakpoints on async functions with function names.

  • gh-74389: Quando a entrada padrão (stdin) usada por uma instância de subprocess.Popen é fechada, isso agora é ignorado em subprocess.Popen.communicate(), em vez de deixar a classe em um estado inconsistente.

  • gh-87512: Corrige o tratamento do limite de tempo de subprocess.Popen.communicate() no Windows ao escrever entradas grandes. Anteriormente, o timeout era ignorado durante a escrita na entrada padrão (stdin), fazendo com que o método bloqueasse indefinidamente se o processo filho não consumisse a entrada rapidamente. Agora, a escrita na entrada padrão é realizada em uma thread em segundo plano, permitindo que o tempo limite seja aplicado corretamente.

  • gh-141939: Add color to all interpolated values in argparse help, like %(default)s or %(choices)s. Patch by Alex Prengère.

  • gh-141473: Quando o método subprocess.Popen.communicate() é chamado com um valor de entrada e um tempo limite definido, e é chamado uma segunda vez após uma exceção TimeoutExpired antes que o processo seja encerrado, ele não deve mais travar.

  • gh-141999: Correctly allow KeyboardInterrupt to stop the process when using profiling.sampling.

  • gh-142006: Corrige um bug no algoritmo de recolhimento do mod email.policy.default que resultava incorretamente em uma quebra de linha duplicada quando uma linha que terminava exatamente em max_line_length era seguida por um token que podia ser desdobrado.

  • gh-141968: Remove data copy from re compilation of regexes with large charsets by using bytearray.take_bytes().

  • gh-141968: Remove data copy from encodings.idna encode() and encode() by using bytearray.take_bytes().

  • gh-141968: Remove data copy from codecs punycode encoding by using bytearray.take_bytes().

  • gh-141968: Remove data copy from wave.Wave_read.readframes() and wave.Wave_write.writeframes() by using bytearray.take_bytes().

  • gh-141968: Remove a data copy from base64.b32decode() and base64.b32encode() by using bytearray.take_bytes().

  • gh-59000: Fix pdb breakpoint resolution for class methods when the module defining the class is not imported.

  • gh-116738: Corrige problema de segurança de threads com objetos scanners de re em construções com threads livres.

  • gh-138122: The profiling.sampling flamegraph profiler now displays thread status statistics showing the percentage of time threads spend holding the GIL, running without the GIL, waiting for the GIL, and performing garbage collection. These statistics help identify GIL contention and thread behavior patterns. When filtering by thread, the display shows per-thread metrics.

  • gh-141781: Fixed an issue where pdb.line_prefix assignment was ignored if assigned after the module was imported.

  • gh-141863: Update Streams to use bytearray.take_bytes() for a over 10% performance improvement on pyperformance asyncio_tcp benchmark.

  • gh-141817: Add socket.IPV6_HDRINCL constant.

  • gh-105836: Fix asyncio.run_coroutine_threadsafe() leaving underlying cancelled asyncio task running.

  • gh-141570: Suporte para objeto arquivo ou similar que levanta OSError de fileno() na detecção de cores (_colorize.can_colorize()). Isso pode ocorrer quando sys.stdout é redirecionado.

  • gh-141679: Add colour to defaults in argparse help. Patch by Hugo van Kemenade.

  • gh-141686: Break reference cycles created by each call to json.dump() or json.JSONEncoder.iterencode().

  • gh-141659: Corrige erros de descritor de arquivo inválido provenientes do processo _posixsubprocess no AIX.

  • gh-141645: Add a new --live mode to the tachyon profiler in profiling.sampling module. This mode consist of a live TUI that displays real-time profiling statistics as the target application runs, similar to top. Patch by Pablo Galindo

  • gh-141615: Check stdin instead of stdout for use_rawinput in pdb.

  • gh-69113: Fix doctest to correctly report line numbers for doctests in __test__ dictionary when formatted as triple-quoted strings by finding unique lines in the string and matching them in the source file.

  • gh-141600: Corrigeoa detecção da versão musl no Void Linux.

  • gh-48752: Add readline.get_pre_input_hook() function to retrieve the current pre-input hook. This allows applications to save and restore the hook without overwriting user settings. Patch by Sanyam Khurana.

  • gh-141565: Add async-aware profiling to the Tachyon sampling profiler. The profiler now reconstructs and displays async task hierarchies in flamegraphs, making the output more actionable for users. Patch by Savannah Ostrowski and Pablo Galindo Salgado.

  • gh-60107: Remove a copy from io.RawIOBase.read(). If the underlying I/O class keeps a reference to the mutable memory, raise a BufferError.

  • gh-116738: Torna o módulo csv seguro para thread na construção com threads livres.

  • gh-140911: collections: Garante que os métodos UserString.rindex() e UserString.index() aceitem instâncias de collections.UserString como sub-argumento.

  • gh-140875: Corrigido o tratamento de referências de caracteres não fechadas (nomeadas e numéricas) seguidas pelo fim do arquivo em html.parser.HTMLParser com convert_charrefs=False.

  • gh-140677: Add heatmap visualization mode to the Tachyon sampling profiler. The new --heatmap output format provides a line-by-line view showing execution intensity with color-coded samples, inline statistics, and interactive call graph navigation between callers and callees.

  • gh-139946: Distinguish stdout and stderr when colorizing output in argparse module.

  • gh-76007: pydoc: Fix DeprecationWarning being raised when generating doc for stdlib modules.

  • gh-138697: Fix inferring dest from a single-dash long option in argparse. If a short option and a single-dash long option are passed to add_argument(), dest is now inferred from the single-dash long option.

  • gh-138525: Add support for single-dash long options and alternate prefix characters in argparse.BooleanOptionalAction.

  • gh-79986: Add parsing for References and In-Reply-To headers to the email library that parses the header content as lists of message id tokens. This prevents them from being folded incorrectly.

  • gh-135559: Flag: a dir() on a Flag enumeration now shows non-canonical members. (i.e. aliases).

  • gh-134453: Corrigido o tratamento de input= da função subprocess.Popen.communicate() por instâncias de memoryview que não tinham formato de bytes em plataformas POSIX. Agora, essas instâncias são convertidas corretamente para uma visualização em formato de byte, em vez de truncar a entrada. Plataformas Windows não apresentavam esse bug.

  • gh-127930: Add __all__ to tkinter.simpledialog.

  • gh-115952: Fix a potential memory denial of service in the pickle module. When reading a pickled data received from untrusted source, it could cause an arbitrary amount of memory to be allocated, even if the code that is allowed to execute is restricted by overriding the find_class() method. This could have led to symptoms including a MemoryError, swapping, out of memory (OOM) killed processes or containers, or even system crashes.

  • bpo-40350: Fix support for namespace packages in modulefinder.

Documentação

Núcleo e embutidos

  • gh-134584: Eliminate redundant refcounting from _STORE_ATTR_INSTANCE_VALUE.

  • gh-142718: JIT: Fix segfault caused by not flushing the stack to memory at side exits.

  • gh-142737: Tracebacks will be displayed in fallback mode even if io.open() is lost. Previously, this would crash the interpreter. Patch by Bartosz Sławecki.

  • gh-116738: Make the attributes in bz2 thread-safe on the free threaded build.

  • gh-134584: Eliminate redundant refcounting from _CALL_LIST_APPEND.

  • gh-142554: Fix a crash in divmod() when _pylong.int_divmod() does not return a tuple of length two exactly. Patch by Bénédikt Tran.

  • gh-142531: Fix a free-threaded GC performance regression. If there are many untracked tuples, the GC will run too often, resulting in poor performance. The fix is to include untracked tuples in the “long lived” object count. The number of frozen objects is also now included since the free-threaded GC must scan those too.

  • gh-142402: Fix reference counting when adjacent literal parts are merged while constructing string.templatelib.Template, preventing the displaced string object from leaking.

  • gh-116738: Make the attributes in zlib thread-safe on the free threaded build.

  • gh-142343: Fix SIGILL crash on m68k due to incorrect assembly constraint.

  • gh-142236: Improve the “Perhaps you forgot a comma?” syntax error for multi-line string concatenations to point to the last string instead of the first, making it easier to locate where the comma is missing. Patch by Pablo Galindo.

  • gh-142236: Fix incorrect keyword suggestions for syntax errors in traceback. The keyword typo suggestion mechanism would incorrectly suggest replacements when the extracted source code was incomplete rather than containing an actual typo. Patch by Pablo Galindo.

  • gh-142305: Decrease the size of the generated stencils and the runtime JIT code. Patch by Diego Russo.

  • gh-135379: Implement a limited form of register allocation known as “top of stack caching” in the JIT. It works by keeping 0-3 of the top items in the stack in registers. The code generator generates multiple versions of those uops that do not escape and are relatively small. During JIT compilation, the copy that produces the least memory traffic is selected, spilling or reloading values when needed.

  • gh-142276: Fix missing type watcher when promoting attribute loads to constants in the JIT. Patch by Ken Jin. Reproducer by Yuancheng Jiang.

  • gh-142218: Fix crash when inserting into a split table dictionary with a non str key that matches an existing key.

  • gh-141976: Check against abstract stack overflow in the JIT optimizer.

  • gh-97850: Remove all *.load_module() usage and definitions from the import system and importlib. The method has been deprecated in favor of importlib.abc.Loader.exec_module() since Python 3.4.

  • gh-142048: Fix quadratically increasing garbage collection delays in free-threaded build.

  • gh-65961: Stop setting __cached__ on modules.

  • gh-141770: Annotate anonymous mmap usage only when supported by the Linux kernel and if -X dev is used or Python is built in debug mode. Patch by Donghee Na.

  • gh-142029: Raise ModuleNotFoundError instead of crashing when a nonexistent module is used as a name in _imp.create_builtin().

  • gh-142029: Raise ValueError instead of crashing when empty string is used as a name in _imp.create_builtin().

  • gh-141976: Protect against specialization failures in the tracing JIT compiler for performance reasons.

  • gh-141861: Fix invalid memory read in the ENTER_EXECUTOR instruction.

  • gh-141930: When importing a module, use Python’s regular file object to ensure that writes to .pyc files are complete or an appropriate error is raised.

  • gh-138122: Add incomplete sample detection to prevent corrupted profiling data. Each thread state now contains an embedded base frame (sentinel at the bottom of the frame stack) with owner type FRAME_OWNED_BY_INTERPRETER. The profiler validates that stack unwinding terminates at this sentinel frame. Samples that fail to reach the base frame (due to race conditions, memory corruption, or other errors) are now rejected rather than being included as spurious data.

  • gh-120158: Corrige estado inconsistente ao habilitar e desabilitar eventos de monitoramento muitas vezes.

  • gh-140638: Expose a "candidates" stat in gc.get_stats() and gc.callbacks.

  • gh-141780: Fix Py_mod_gil with API added in PEP 793: PyModule_FromSlotsAndSpec() and PyModExport hooks

  • gh-141732: Ensure the __repr__() for ExceptionGroup and BaseExceptionGroup does not change when the exception sequence that was original passed in to its constructor is subsequently mutated.

  • gh-140638: Expose a "duration" stat in gc.get_stats() and gc.callbacks.

  • gh-139653: Somente levanta um erro RecursionError ou aciona um erro fatal se o ponteiro da pilha estiver abaixo do ponteiro limite e acima da base da pilha. Se estiver fora desses limites, presume que está tudo bem. Isso evita falsos positivos quando threads do espaço do usuário trocam pilhas.

  • gh-41779: Allowed defining the __dict__ and __weakref__ __slots__ for any class.

  • gh-139103: Melhora a escalabilidade multithread das classes de dados na construção com threads livres.

  • gh-141589: Change backoff counter to use prime numbers instead of powers of 2. Use only 3 bits for counter and 13 bits for value. This allows to support values up to 8191. Patch by Mikhail Efimov.

  • gh-137007: Fix a bug during JIT compilation failure which caused garbage collection debug assertions to fail.

  • gh-132657: For the free-threaded build, avoid locking the set object for the __contains__ method.

  • gh-134584: Eliminate redundant refcounting from _CALL_STR_1.

  • gh-134584: Eliminate redundant refcounting from _CALL_BUILTIN_O.

  • gh-134584: Eliminate redundant refcounting from _CALL_TUPLE_1. Patch by Noam Cohen

API C

Construção

  • gh-131372: Add LDVERSION and EXE to the base_interpreter value of build-details.json.

  • gh-142454: When calculating the digest of the JIT stencils input, sort the hashed files by filenames before adding their content to the hasher. This ensures deterministic hash input and hence deterministic hash, independent on filesystem order.

  • gh-131372: build-details.py will only be installed as part of the main install (make install). make altinstall will no longer include it.

  • gh-142234: Allow --enable-wasm-dynamic-linking for WASI. While CPython doesn’t directly support it so external/downstream users do not have to patch in support for the flag.

  • gh-142050: Fixed a bug where JIT stencils produced on Windows contained debug data. Patch by Chris Eibl.

  • gh-141808: Do not generate the jit stencils twice in case of PGO builds on Windows.

  • gh-141926: RUNSHARED is no longer cleared when cross-compiling. Previously, RUNSHARED was cleared when cross-compiling, which breaks PGO when using --enabled-shared on systems where the cross-compiled CPython is otherwise executable (e.g., via transparent emulation).

  • gh-141808: When running make clean-retain-profile, keep the generated JIT stencils. That way, the stencils are not generated twice when Profile-guided optimization (PGO) is used. It also allows distributors to supply their own pre-built JIT stencils.

  • gh-141784: Correção na construção de _remote_debugging_module.c em Linux de 32 bits. Inclusão de Python.h antes dos cabeçalhos do sistema para garantir que _remote_debugging_module.c utilize os mesmos tipos (ABI) que o Python. Patch por Victor Stinner.

  • gh-141172: Update to WASI SDK 29.

  • gh-139707: Add configure option --with-missing-stdlib-config=FILE allows which distributors to pass a JSON configuration file containing custom error messages for missing standard library modules.

  • gh-108819: Honor --with-platlibdir in the pure-Python standard library installation path, if PLATLIBDIR doesn’t match the value used in LIBDIR.

Python 3.15.0 alpha 2

Release date: 2025-11-18

Windows

  • gh-140849: Update bundled liblzma to version 5.8.1.

Ferramentas/Demos

  • gh-141442: O ambiente de testes do iOS agora lida corretamente com argumentos de teste que contêm espaços.

  • gh-140702: A aplicação de teste para iOS agora exporá a variável de ambiente GITHUB_ACTIONS para os aplicativos iOS que estão sendo testados.

  • gh-139198: Remove Tools/scripts/checkpip.py script.

  • gh-139188: Remove Tools/tz/zdump.py script.

Testes

  • gh-140482: Preserva e restaura o estado de stty echo como parte do ambiente de teste.

  • gh-140082: Atualiza o comando python -m test para definir FORCE_COLOR=1 quando executado com cores ativadas, para que o unittest, executado por ele com saída redirecionada, seja exibido em cores.

  • gh-136442: Usa o código de saída 1 em vez de 5 se a unittest.TestCase.setUpClass() levantar uma exceção.

Segurança

Biblioteca

  • gh-141497: ipaddress: garante que os métodos IPv4Network.hosts() e IPv6Network.hosts() sempre retornem um iterador.

  • gh-140938: As funções statistics.stdev() e statistics.pstdev() agora levantam ValueError quando a entrada contém um infinito ou um NaN.

  • gh-124111: Atualizada a configuração de threads do Tcl em _tkinter para presumir que threads estão sempre disponíveis no Tcl 9 e versões posteriores.

  • gh-137109: O os.fork e as APIs de fork relacionadas não emitirão mais avisos no caso comum em que as APIs da plataforma Linux ou macOS retornam o número de threads em um processo e encontram a resposta como 1, mesmo quando um função de retorno os.register_at_fork() after_in_parent= (re)inicia uma thread.

  • gh-141314: Corrigido o erro de asserção em io.TextIOWrapper.tell() ao ler arquivos com quebras de linha de retorno de carro isoladas (\r).

  • gh-141311: Corrigido o erro de asserção em io.BytesIO.readinto() e o comportamento indefinido que ocorria quando a posição de leitura estava acima da capacidade em io.BytesIO.

  • gh-87710: mimetypes: Update mime type for .ai files to application/pdf.

  • gh-85524: Update io.FileIO.readall, an implementation of io.RawIOBase.readall(), to follow io.IOBase guidelines and raise io.UnsupportedOperation when a file is in “w” mode rather than OSError

  • gh-141141: Corrige um problema de segurança de threads com base64.b85decode(). Contribuição de Benel Tayar.

  • gh-141018: mimetypes: Update .exe, .dll, .rtf and (when strict=False) .jpg to their correct IANA mime type.

  • gh-137969: Corrigido o método annotationlib.ForwardRef.evaluate() que retorna objetos ForwardRef que não são atualizados com novas variáveis globais.

  • gh-75593: Add support of path-like objects and bytes-like objects in wave.open().

  • gh-140797: A classe não documentada re.Scanner agora proíbe expressões regulares que contenham grupos de captura em seus padrões de léxico. Padrões que utilizavam grupos de captura podiam anteriormente causar falhas de segmentação. Em vez disso, utilize grupos sem captura (?:…).

  • gh-125115: Refatora a correção do problema de análise sintática do pdb para que os argumentos posicionais possam ser passados de forma intuitiva.

  • gh-140815: faulthandler agora detecta se um quadro ou um objeto código é inválido ou foi liberado. Patch por Victor Stinner.

  • gh-100218: Define corretamente errno quando as socket.if_nametoindex() ou socket.if_indextoname() levantam OSError. Patch por Bénédikt Tran.

  • gh-140734: multiprocessing: Corrige erro de diferença de um bit ao verificar o comprimento do caminho de um arquivo de socket temporário. Patch por Bénédikt Tran.

  • gh-140873: Add support of non-descriptor callables in functools.singledispatchmethod().

  • gh-140874: Atualiza a versão do pip empacotado no ensurepip para a versão 25.3.

  • gh-140826: Now winreg.HKEYType objects are compared by their underlying Windows registry handle value instead of their object identity.

  • gh-140808: The internal class mailbox._ProxyFile is no longer a parameterized generic.

  • gh-140691: Em urllib.request, quando a abertura de um URL FTP falha porque não é possível estabelecer uma conexão de dados, o socket da conexão de controle é agora fechado para evitar um ResourceWarning.

  • gh-103847: Corrigido o travamento que ocorria ao cancelar um processo criado por asyncio.create_subprocess_exec() ou asyncio.create_subprocess_shell(). Patch por Kumar Aditya.

  • gh-137821: Convert _json module to use Argument Clinic. Patched by Yoonho Hann.

  • gh-140790: Initialize all Pdb’s instance variables in __init__, remove some hasattr/getattr

  • gh-140766: Add enum.show_flag_values() and enum.bin to enum.__all__.

  • gh-120057: Adiciona os.reload_environ() para os.__all__.

  • gh-140741: Fix profiling.sampling.sample() incorrectly handling a FileNotFoundError or PermissionError.

  • gh-140228: Evita fazer chamadas desnecessárias ao sistema de arquivos para módulos congelados em linecache quando o cache de módulos global não estiver presente.

  • gh-139946: Error and warning keywords in argparse.ArgumentParser messages are now colorized when color output is enabled, fixing a visual inconsistency in which they remained plain text while other output was colorized.

  • gh-140590: Correção na verificação de argumentos para o método functools.partial.__setstate__(), que pode levar à corrupção do estado interno e ao travamento do sistema. Patch por Sergey Miryanov.

  • gh-125434: Exibe o nome da thread em faulthandler no Windows. Patch por Victor Stinner.

  • gh-140634: Corrige um bug de contagem de referências em os.sched_param.__reduce__().

  • gh-140650: Fix an issue where closing io.BufferedWriter could crash if the closed attribute raised an exception on access or could not be converted to a boolean.

  • gh-140633: Ignora AttributeError ao definir o atributo __file__ de um módulo ao carregar um módulo de extensão empacotado como Apple Framework.

  • gh-140601: xml.etree.ElementTree.iterparse() now emits a ResourceWarning when the iterator is not explicitly closed and was opened with a filename. This helps developers identify and fix resource leaks. Patch by Osama Abdelkader.

  • gh-140593: xml.parsers.expat: Corrige um vazamento de memória que poderia afetar usuários com ElementDeclHandler() definido como um manipulador de declaração de elemento personalizado. Patch por Sebastian Pipping.

  • gh-140607: Dentro de io.RawIOBase.read(), verifica se a contagem de bytes retornada por io.RawIOBase.readinto() é válida (dentro do buffer fornecido).

  • gh-138162: Corrige logging.LoggerAdapter com merge_extra=True e sem o argumento extra.

  • gh-140481: Improve error message when trying to iterate a Tk widget, image or font.

  • gh-138774: ast.unparse() agora gera código-fonte completo ao manipular nós ast.Interpolation que não têm uma fonte especificada.

  • gh-140474: Corrige vazamento de memória em array.array ao criar vetores a partir de um objeto str vazio e do código do tipo u.

  • gh-140448: Change the default of suggest_on_error to True in argparse.ArgumentParser.

  • gh-137530: dataclasses: Corrige as anotações dos métodos __init__ gerados, substituindo as anotações que estavam embutidas no código-fonte gerado por funções __annotate__ anexadas aos métodos.

  • gh-140348: Corrige uma regressão no Python 3.14.0 em que o uso do operador | em um objeto typing.Union combinado com um objeto que não é um tipo levantava um erro.

  • gh-76007: decimal: Deprecate __version__ and replace with decimal.SPEC_VERSION.

  • gh-76007: Deprecate __version__ from imaplib. Patch by Hugo van Kemenade.

  • gh-140272: Corrige vazamento de memória no método clear() do banco de dados dbm.gnu.

  • gh-129117: unicodedata: Add isxidstart() and isxidcontinue() functions to check whether a character can start or continue a Unicode Standard Annex #31 identifier.

  • gh-140251: Colorize the default import statement import asyncio in asyncio REPL.

  • gh-140212: Calendar’s HTML formatting now accepts year and month as options. Previously, running python -m calendar -t html 2025 10 would result in an error message. It now generates an HTML document displaying the calendar for the specified month. Contributed by Pål Grønås Drange.

  • gh-135801: Improve filtering by module in warnings.warn_explicit() if no module argument is passed. It now tests the module regular expression in the warnings filter not only against the filename with .py stripped, but also against module names constructed starting from different parent directories of the filename (with /__init__.py, .py and, on Windows, .pyw stripped).

  • gh-139707: Improve ModuleNotFoundError error message when a standard library module is missing.

  • gh-140041: Corrige importação de ctypes no Android e Cygwin quando sinalizadores ABI estiverem presentes.

  • gh-140120: Corrigido um vazamento de memória em hmac ao usar o backend hacl-star. Descoberto por @ashm-dev usando AddressSanitizer.

  • gh-140141: The importlib.metadata.PackageNotFoundError traceback raised when importlib.metadata.Distribution.from_name cannot discover a distribution no longer includes a transient StopIteration exception trace.

    Contributed by Bartosz Sławecki in gh-140142.

  • gh-140166: mimetypes: Per the IANA assignment, update the MIME type for the .texi and .texinfo file formats to application/texinfo, instead of application/x-texinfo.

  • gh-140135: Speed up io.RawIOBase.readall() by using PyBytesWriter API (about 4x faster)

  • gh-76007: zlib: Deprecate __version__ and schedule for removal in Python 3.20.

  • gh-136702: encodings: Deprecate passing a non-ascii encoding name to encodings.normalize_encoding() and schedule removal of support for Python 3.17.

  • gh-139940: Print clearer error message when using pdb to attach to a non-existing process.

  • gh-139462: When a child process in a concurrent.futures.ProcessPoolExecutor terminates abruptly, the resulting traceback will now tell you the PID and exit code of the terminated process. Contributed by Jonathan Berg.

  • gh-63161: Corrige tokenize.detect_encoding(). Suporte a shebang e comentários não UTF-8 se a codificação não UTF-8 for especificada. Detecta erro de decodificação para codificação não UTF-8. Detecta bytes nulos no código-fonte.

  • gh-101828: Corrige os codecs 'shift_jisx0213', 'shift_jis_2004', 'euc_jisx0213' e 'euc_jis_2004' que truncavam caracteres nulos, pois eram tratados como parte de sequências de múltiplos caracteres.

  • gh-139246: correção: colar texto com largura zero na largura padrão do REPL está incorreto.

  • gh-83714: Implement os.statx() on Linux kernel versions 4.11 and later with glibc versions 2.28 and later. Contributed by Jeffrey Bosboom and Victor Stinner.

  • gh-138891: Corrige SyntaxError quando inspect.get_annotations(f, eval_str=True) for chamado em uma função anotada com star_expression da PEP 646

  • gh-138859: Corrige a parametrização de tipo genérico levantando TypeError ao omitir uma ParamSpec que tem um padrão que não é uma lista de tipos.

  • gh-138764: Impede que annotationlib.call_annotate_function() chame funções __annotate__ que não ofereçam suporte a VALUE_WITH_FAKE_GLOBALS em um espaço de nomes globals falso com globais vazios.

    Faz com que as anotações FORWARDREF e STRING voltem a usar anotações VALUE no caso de nem seu próprio formato nem VALUE_WITH_FAKE_GLOBALS serem suportados.

  • gh-138775: O uso de python -m com base64 foi corrigido para detectar a entrada de um terminal, de forma que reconheça corretamente o EOF (fim de arquivo).

  • gh-98896: Corrige um erro em resource_tracker do módulo multiprocessing quando os nomes de SharedMemory contêm dois pontos. Patch por Rani Pinchuk.

  • gh-138425: Corrige avaliação parcial de objetos annotationlib.ForwardRef que dependem de nomes definidos como globais.

  • gh-138151: Em annotationlib, aprimora-se a avaliação de referências futuras a variáveis não locais que ainda não estão definidas quando as anotações são avaliadas inicialmente.

  • gh-69528: The mode attribute of files opened in the 'wb+' mode is now 'wb+' instead of 'rb+'.

  • gh-137627: Speed up csv.Sniffer.sniff() delimiter detection by up to 1.6x.

  • gh-55531: encodings: Improve normalize_encoding() performance by implementing the function in C using the private _Py_normalize_encoding which has been modified to make lowercase conversion optional.

  • gh-136057: Corrigido o bug em pdb e bdb onde next e step não conseguiam ultrapassar a linha se existisse um laço na linha.

  • gh-133390: Support table, index, trigger, view, column, function, and schema completion for sqlite3’s command-line interface.

  • gh-135307: email: Corrige a exceção em set_content() ao codificar texto quando max_line_length está definido como 0 ou None (ilimitado).

  • gh-133789: Corrige a desserialização com pickle de objetos pathlib que foram serializados com pickle no Python 3.13.

  • gh-133601: Remove deprecated typing.no_type_check_decorator().

  • gh-132686: Add parameters inherit_class_doc and fallback_to_class_doc for inspect.getdoc().

  • gh-131116: inspect.getdoc() now correctly returns an inherited docstring on cached_property objects if none is given in a subclass.

  • gh-130693: Add support for -nolinestop, and -strictlimits options to tkinter.Text.search(). Also add the tkinter.Text.search_all() method for -all and -overlap options.

  • gh-122255: In the linecache module and in the Python implementation of the warnings module, a DeprecationWarning is issued when mod.__loader__ differs from mod.__spec__.loader (like in the C implementation of the warnings module).

  • gh-121011: math.log() now supports arbitrary large integer-like arguments in the same way as arbitrary large integer arguments.

  • gh-119668: Publicly expose and document importlib.machinery.NamespacePath.

  • gh-102431: Esclarece restrições para argumentos “lógicos” em métodos de decimal.Context.

  • gh-81313: Add the math.integer module (PEP 791).

Núcleo e embutidos

  • gh-141579: Corrigido o problema na função sys.activate_stack_trampoline() para que ela ofereça suporte correto ao backend perf_jit. Patch por Pablo Galindo.

  • gh-114203: Ignora a trava se o objeto já estiver travado por uma seção crítica de dois mutexes.

  • gh-141528: Sugere o uso de concurrent.interpreters.Interpreter.close() em vez da função privada _interpreters.destroy ao emitir avisos sobre subinterpretadores restantes. Patch por Sergey Miryanov.

  • gh-141367: Specialize CALL_LIST_APPEND instruction only for lists, not for list subclasses, to avoid unnecessary deopt. Patch by Mikhail Efimov.

  • gh-141312: Corrige a falha de asserção no método __setstate__ do iterador de intervalo quando um argumento não inteiro é passado. Patch por Sergey Miryanov.

  • gh-140643: Add support for <GC> and <native> frames to profiling.sampling output to denote active garbage collection and calls to native code.

Biblioteca

  • gh-140942: Add .cjs to mimetypes to give CommonJS modules a MIME type of application/node.

Núcleo e embutidos

  • gh-140479: Update JIT compilation to use LLVM 21 at build time.

  • gh-140939: Corrige vazamento de memória quando bytearray ou bytes é formatado com o formato %*b com uma largura grande que resulta em uma MemoryError.

Biblioteca

  • gh-140260: Correção de condição de corrida de dados em struct na inicialização de tabelas endian com subinterpretadores. Patch por Shamil Abdulaev.

Núcleo e embutidos

  • gh-140530: Corrige um vazamento de referência que ocorria quando raise exc from cause falhava. Patch por Bénédikt Tran.

Biblioteca

Núcleo e embutidos

  • gh-140373: Correctly emit PY_UNWIND event when generator object is closed. Patch by Mikhail Efimov.

  • gh-140729: Fix pickling error in the sampling profiler when using concurrent.futures.ProcessPoolExecutor script can not be properly pickled and executed in worker processes.

  • gh-131527: Dynamic borrow checking for stackrefs is added to Py_STACKREF_DEBUG mode. Patch by Mikhail Efimov.

  • gh-140576: Corrigido o erro que causava o fechamento inesperado do código em tokenize.generate_tokens() em caso de entrada incorreta específica. Patch por Mikhail Efimov.

  • gh-140544: Speed up accessing interpreter state by caching it in a thread local variable. Patch by Kumar Aditya.

  • gh-140551: Corrigido o problema que causava o fechamento inesperado do arquivo dict se o método dict.clear() fosse chamado na fase de busca. Patch por Mikhail Efimov e Inada Naoki.

  • gh-140517: Corrigido um vazamento de referência ao iterar sobre o resultado de map() com strict=True quando os iteráveis de entrada tinham comprimentos diferentes. Patch por Mikhail Efimov.

  • gh-133467: Fix race when updating type.__bases__ that could allow a read of type.__base__ to observe an inconsistent value on the free threaded build.

  • gh-140471: Corrige possível estouro de buffer na inicialização do nó ast.AST ao encontrar _fields malformados contendo não-str.

Biblioteca

  • gh-140443: The logarithm functions (such as math.log10() and math.log()) may now produce slightly different results for extremely large integers that cannot be converted to floats without overflow. These results are generally more accurate, with reduced worst-case error and a tighter overall error distribution.

Núcleo e embutidos

Biblioteca

Núcleo e embutidos

  • gh-140406: Corrige vazamento de memória quando o método __hash__() de um objeto retorna um objeto que não é um int.

  • gh-140358: Restaura o tempo decorrido e a contagem de objetos inacessíveis na saída de depuração do GC. Esses dados foram removidos inadvertidamente durante uma refatoração de gc.c. O log de depuração agora relata novamente o tempo de coleta decorrido e o número de objetos inacessíveis. Contribuição de Pål Grønås Drange.

  • gh-136895: Update JIT compilation to use LLVM 20 at build time.

  • gh-139109: A new tracing frontend for the JIT compiler has been implemented. Patch by Ken Jin. Design for CPython by Ken Jin, Mark Shannon and Brandt Bucher.

  • gh-140306: Corrige vazamentos de memória em operações de canal entre interpretadores e manipulação de espaço de nomes compartilhado.

  • gh-116738: Make _suggestions module thread-safe on the free threaded build.

  • gh-140301: Corrige vazamento de memória de PyConfig em subinterpretadores.

  • gh-140257: Corrige corrida de dados entre interpreter_clear() e take_gil() em eval_breaker durante a finalização com threads daemon.

  • gh-139951: Corrige uma regressão no desempenho do GC para um heap crescente composto principalmente de pequenas tuplas.

    • Conta o número de objetos realmente rastreados, em vez de objetos rastreáveis. Isso garante que o cancelamento do rastreamento de tuplas tenha o efeito desejado de reduzir a sobrecarga do coletor de lixo.

    • Não rastreia a maioria das tuplas não rastreáveis durante a criação. Isso evita que um grande número de tuplas pequenas causem GCs excessivos.

  • gh-140253: Wrong placement of a double-star pattern inside a mapping pattern now throws a specialized syntax error. Contributed by Bartosz Sławecki in gh-140253.

  • gh-140104: Correção de um bug no tratamento de exceções no JIT. Patch por Ken Jin. Bug relatado por Daniel Diniz.

  • gh-140149: Speed up parsing bytes literals concatenation by using PyBytesWriter API and a single memory allocation (about 3x faster).

  • gh-140061: Correção da verificação de se um objeto é referenciado exclusivamente para garantir compatibilidade com threads livres. Patch por Sergey Miryanov.

  • gh-140080: Fix hang during finalization when attempting to call atexit handlers under no memory.

  • gh-139871: Update bytearray to use a bytes under the hood as its buffer and add bytearray.take_bytes() to take it out.

  • gh-140067: Corrige vazamento de memória na criação de subinterpretadores.

  • gh-139914: Restaura o suporte para HP PA-RISC, que possui uma pilha crescente.

  • gh-139817: Attribute __qualname__ is added to typing.TypeAliasType. Patch by Mikhail Efimov.

  • gh-135801: Many functions related to compiling or parsing Python code, such as compile(), ast.parse(), symtable.symtable(), and importlib.abc.InspectLoader.source_to_code() now allow to specify the module name. It is needed to unambiguous filter syntax warnings by module name.

  • gh-139640: ast.parse() não emite mais avisos de sintaxe para return/break/continue em finally (veja PEP 765) – eles são emitidos apenas durante a compilação.

  • gh-139640: Corrige a ingestão de alguns avisos de sintaxe em módulos diferentes caso eles acidentalmente tenham a mesma mensagem e sejam emitidos na mesma linha. Corrige avisos duplicados no bloco finally.

  • gh-139475: Changes in stackref debugging mode when Py_STACKREF_DEBUG is set. We use the same pattern of refcounting for stackrefs as in production build.

  • gh-139269: Fix undefined behavior when using unaligned store in JIT’s patch_* functions.

  • gh-138944: Corrige a mensagem SyntaxError que ocorre quando uma sintaxe inválida aparece na mesma linha que uma instrução import ... as ... ou from ... import ... as ... válida. Patch por Brian Schubert.

  • gh-138857: Improve SyntaxError message for case keyword placed outside match body.

  • gh-131253: Support the --enable-pystats build option for the free-threaded build.

  • gh-136327: Errors when calling functions with invalid values after * and ** now do not include the function name. Patch by Ilia Solin.

  • gh-134786: If Py_TPFLAGS_MANAGED_DICT and Py_TPFLAGS_MANAGED_WEAKREF are used, then Py_TPFLAGS_HAVE_GC must be used as well.

API C

Construção

  • gh-140454: When building the JIT, match the jit_stencils filename expectations in Makefile with the generator script. This avoid needless JIT recompilation during make install.

  • gh-140768: Avisa quando a versão do SDK do WASI não corresponder à versão suportada.

  • gh-140513: Gera um erro de compilação claro quando _Py_TAIL_CALL_INTERP estiver habilitado, mas preserve_none ou musttail não forem suportados.

  • gh-140475: Support WASI SDK 25.

  • gh-140239: Check statx availability only on Linux (including Android).

  • gh-140189: As versões para iOS foram adicionadas à integração contínua.

  • gh-137618: PYTHON_FOR_REGEN agora requer Python 3.10 a Python 3.15. Patch por Adam Turner.

Python 3.15.0 alpha 1

Release date: 2025-10-14

macOS

  • gh-115119: Update macOS installer to use libmpdecimal 4.0.1.

  • gh-124111: Update macOS installer to use Tcl/Tk 9.0.2.

  • gh-132339: Update macOS installer version of OpenSSL to 3.5.4.

  • gh-137450: macOS instalador console melhorias no gerenciamento de caminhos: separe o script pós-instalação do instalador console profile updater do Update console Profile.comando para permitir um manuseio mais robusto do erro.

  • gh-137134: Atualização do instalador do macOS para ser fornecido com o SQLite versão 3.50.4.

Windows

  • gh-139810: A instalação com py install 3[.x]-dev agora selecionará versões finais e também pré-lançamentos.

  • gh-139573: Atualizada a versão empacotada do OpenSSL para 3.0.18.

  • gh-138896: Corrige erro ao instalar o runtime do C em máquinas Windows não atualizadas

  • gh-138314: Add winreg.DeleteTree().

  • gh-137136: Suppress build warnings when build on Windows with --experimental-jit-interpreter.

  • gh-137134: Atualizar o instalador do Windows para que seja fornecido com o SQLite 3.50.4.

  • gh-135099: Corrige uma falha que poderia ocorrer no Windows quando uma thread em segundo plano aguarda um PyMutex enquanto o thread principal está desligando o interpretador.

  • gh-130727: Corrige uma corrida em chamadas internas para o WMI que pode resultar em uma exceção de “identificador inválido” sob carga alta. Patch por Chris Eibl.

  • gh-76023: Faz com que os.path.realpath() ignore o erro 1005 do Windows quando estiver no modo não estrito.

  • gh-133779: Reverte a alteração para gerar arquivos pyconfig.h diferentes com base nas configurações do compilador, pois isso frequentemente causava falhas nas construções de extensões. Em particular, a variável de pré-processador Py_GIL_DISABLED agora deve ser sempre definida explicitamente ao compilar para o tempo de execução experimental de threads livres. A função sysconfig.get_config_var() pode ser usada para determinar se o tempo de execução atual foi compilado com esse sinalizador ou não.

  • gh-133626: Garante que os pacotes não sejam acidentalmente agrupados no instalador tradicional.

  • gh-133580: Fix sys.getwindowsversion() failing without setting an exception when called on some WinAPI partitions.

  • gh-133572: Avoid LsaNtStatus to WinError conversion on unsupported WinAPI partitions.

  • gh-133568: Fix compile error when using a WinAPI partition that doesn’t support the RPC runtime library.

  • gh-133562: Disable handling of security descriptors by os.mkdir() with mode 0o700 on WinAPI partitions that do not support it. This only affects custom builds for specialized targets.

  • gh-133537: Avoid using console I/O in WinAPI partitions that don’t support it

  • gh-131942: Use the Python-specific Py_DEBUG macro rather than _DEBUG in Windows-related C code. Patch by Xuehai Pan.

Ferramentas/Demos

  • gh-139330: A ferramenta de geração de SBOM não verificava os valores de versão e checksum em relação ao script Modules/expat/refresh.sh, o que levava a que os valores ficassem desatualizados durante atualizações de rotina.

  • gh-132006: XCframeworks agora incluem manifestos de privacidade para atender aos requisitos de envio da Apple App Store.

  • gh-138171: Foi adicionado um script para a construção de um framework iOS XC. Como parte dessa alteração, a pasta de nível superior iOS foi movida para um subdiretório da pasta Apple.

  • gh-137873: O executor de testes iOS foi simplificado, resolvendo alguns problemas que foram observados ao usar o executor nos ambientes de teste do GitHub Actions e do Azure Pipelines.

  • gh-137484: Coloca o Tools/wasm/wasi no Python de construção em um diretório com o nome do triplo de construção em vez de “build”.

  • gh-137025: The wasm_build.py script has been removed. Tools/wasm/emscripten and Tools/wasm/wasi should be used instead, as described in the Dev Guide.

  • gh-137248: Adiciona uma opção --logdir em Tools/wasm/wasi para especificar onde gravar os arquivos de log.

  • gh-137243: Faz com que o Tools/wasm/wasi detecte uma instalação do WASI SDK em /opt quando ele foi extraído diretamente de um tarball de lançamento.

  • gh-136251: Correções e melhorias de usabilidade para Tools/wasm/emscripten/web_example

  • gh-135968: Os stubs para strip agora são fornecidos como parte de uma instalação do iOS.

  • gh-135379: The cases generator no longer accepts type annotations on stack items. Conversions to non-default types are now done explicitly in bytecodes.c and optimizer_bytecodes.c. This will simplify code generation for top-of-stack caching and other future features.

  • gh-134215: Autopreenchimento de importação do REPL sugere apenas módulos privados quando explicitamente especificado.

Testes

  • gh-139208: Corrige o regrtest --fast-ci --verbose: não ignora mais a opção --verbose. Patch por Victor Stinner.

  • gh-138313: Restore skipped test and add janky workaround to prevent select buildbots from failing with a ResourceWarning.

  • gh-135966: O ambiente de teste do iOS agora manipula a pasta app_packages como um diretório de site.

  • gh-135494: Corrige o regrtest para suportar a exclusão de testes de --pgo. Patch por Victor Stinner.

  • gh-132815: Corrige test__opcode: adiciona JUMP_BACKWARD às estatísticas de especialização.

  • gh-135489: Exibe saída detalhada para testes com falha durante a etapa de criação de perfil do PGO com –enable-optimizations.

  • gh-135401: Add a new GitHub CI job to test the ssl module with AWS-LC as the backing cryptography and TLS library.

  • gh-135120: Adiciona test.support.subTests().

  • gh-134567: Expose log formatter to users in TestCase.assertLogs. unittest.TestCase.assertLogs() will now optionally accept a formatter that will be used to format the strings in output if provided.

  • gh-133744: Corrigido o teste de interrupção de multiprocessamento. Adicionado um evento para sincronizar o processo pai com o processo filho: aguardar até que o processo filho comece a hibernar. Patch por Victor Stinner.

  • gh-133682: Corrigido caso de teste test.test_annotationlib.TestStringFormat.test_displays que garante o tratamento adequado de estruturas de dados complexas (listas, conjuntos, dicionários e tuplas) em anotações de string.

  • gh-133639: Corrige TestPyReplAutoindent.test_auto_indent_default() não executar input_code.

Segurança

  • gh-139700: Verifica a consistência do registro zip64 no final do diretório central. Suporte a registros com “dados extensíveis zip64” se não houver bytes anexados ao arquivo ZIP.

  • gh-139400: xml.parsers.expat: Garante que os analisadores Expat pais sejam coletados como lixo somente quando não forem mais referenciados por subanalisadores criados por ExternalEntityParserCreate(). Patch por Sebastian Pipping.

  • gh-139283: sqlite3: manipula corretamente o número máximo de linhas a serem buscadas em Cursor.fetchmany e rejeita valores negativos para Cursor.arraysize. Patch por Bénédikt Tran.

  • gh-136053: marshal: corrige uma possível falha ao desserializar objetos slice.

  • gh-135661: Corrige a análise das tags de início e fim em html.parser.HTMLParser de acordo com o padrão HTML5.

    • Espaços em branco não são mais aceitos entre </ e o nome da tag. Por exemplo, </ script> não encerra a seção de script.

    • Tabulação vertical (\v) e espaços em branco não ASCII não são mais reconhecidos como espaços em branco. Os únicos espaços em branco são \t\n\r\f e espaço.

    • O caractere nulo (U+0000) não termina mais o nome da tag.

    • Atributos e barras após o nome da tag em tags finais agora são ignorados, em vez de terminar após o primeiro > no valor do atributo entre aspas. Por exemplo, </script/foo=">"/>.

    • Barras múltiplas e espaços em branco entre o último atributo e o > de fechamento agora são ignorados nas tags de início e fim. Por exemplo, <a foo=bar/ //>.

    • Múltiplos = entre o nome do atributo e o valor não são mais recolhidos. Por exemplo, <a foo==bar> produz o atributo “foo” com o valor “=bar”.

  • gh-135661: Corrige a análise da seção CDATA em html.parser.HTMLParser de acordo com o padrão HTML5: ] ]> e ]] > não encerram mais a seção CDATA. Adiciona o método privado _set_support_cdata(), que pode ser usado para especificar como analisar <[CDATA[ — como uma seção CDATA em conteúdo externo (SVG ou MathML) ou como um comentário falso no espaço de nomes HTML.

  • gh-102555: Corrige a análise de comentários em html.parser.HTMLParser de acordo com o padrão HTML5. --!> agora encerra o comentário. -- > não encerra mais o comentário. Suporte a comentários vazios <--> e <---> que encerravam anormalmente.

  • gh-135462: Corrigida a complexidade quadrática no processamento de entradas especialmente criadas em html.parser.HTMLParser. Erros de fim de arquivo agora são tratados de acordo com as especificações do HTML5 – comentários e declarações são fechados automaticamente, tags são ignoradas.

  • gh-118350: Corrige suporte ao modo de texto bruto escapável (elementos “textarea” e “title”) em html.parser.HTMLParser.

  • gh-135034: Corrige vários problemas que permitiam que os filtros de extração tarfile (filter="data" e filter="tar") fossem ignorados usando links simbólicos e links físicos criados.

    Endereços CVE 2024-12718, CVE 2025-4138, CVE 2025-4330 e CVE 2025-4517.

  • gh-133767: Corrige uso após liberação no decodificador “unicode-escape” com um tratador de erros não “estrito”.

  • gh-133623: Indicate through ssl.HAS_PSK_TLS13 whether the ssl module supports “External PSKs” in TLSv1.3, as described in RFC 9258. Patch by Will Childs-Klein.

  • gh-128840: Faz um curto-circuito no processamento de endereços IPv6 longos no início de ipaddress para evitar consumo excessivo de memória e uma pequena negação de serviço.

Biblioteca

IDLE

  • gh-96491: Desduplica o número da versão na barra de título do shell do IDLE após salvar em um arquivo.

  • gh-139742: Colore prefixos de t-string para strings template no IDLE, como feito para prefixos de f-string.

Documentação

  • gh-136155: Agora estamos verificando erros fatais em construções de EPUB no CI.

  • gh-135171: Documenta que o iterador para a cláusula for mais à esquerda na expressão geradora é criado imediatamente.

  • bpo-45210: Documenta que o indicador de erro pode ser definido em tp_dealloc e como evitar sobrecarregá-lo.

Núcleo e embutidos

  • gh-140000: Corrige possível vazamento de memória quando há um ciclo de referência entre uma instância de typing.TypeAliasType, typing.TypeVar, typing.ParamSpec ou typing.TypeVarTuple e seu atributo __name__. Patch por Mikhail Efimov.

  • gh-140009: Improve performance of list extension by dictionary items.

  • gh-139988: Corrige um vazamento de memória causado pela falha na criação do tipo Union. Patch por Bénédikt Tran.

  • gh-139748: Corrige vazamentos de referência em ramificações de erro de funções que aceitam strings de caminho ou bytes, como compile() e os.system(). Patch por Bénédikt Tran.

  • gh-139516: Corrigir erro no formato de início de especificação de dois pontos lambda na f-string no tokenizador.

  • gh-63161: Suporte a shebang e comentários não UTF-8 em arquivos-fonte Python se a codificação não UTF-8 for especificada. Detecte erros de decodificação em comentários para a codificação padrão (UTF-8). Exibe a linha e a posição do erro de decodificação para a codificação padrão em um traceback. Exiba a linha que contém o cookie de codificação quando ele entrar em conflito com o BOM em um traceback.

  • gh-139116: Prevent a deadlock when multiple threads start, stop and use tracemalloc simultaneously.

  • gh-139275: Fix compilation problems in _remote_debugging_module.c when the system doesn’t have process_vm_readv. Patch by Pablo Galindo

  • gh-133059: Increased the number of cached small positive integers from 256 to 1024.

  • gh-74857: PEP 538: Coerce the POSIX locale to a UTF-8 based locale. Patch by Victor Stinner.

Biblioteca

Núcleo e embutidos

  • gh-138558: Corrige o tratamento de anotações incomuns de t-string na annotationlib. Patch por Dave Peck.

  • gh-134466: Não executa o PyREPL em um ambiente degradado onde a definição de atributos termios não é permitida.

  • gh-138794: When a new tracing function is registered with PyRefTracer_SetTracer(), replacing the current a call to the trace function will be made with the object set to NULL and event set to PyRefTracer_TRACKER_REMOVED. This will happen just before the new function is registered. Patch by Pablo Galindo

  • gh-71810: Levanta OverflowError para (-1).to_bytes() para conversões com sinal quando a contagem de bytes for zero. Patch por Sergey B Kirpichev.

  • gh-138716: Improve SyntaxError message for assert in cases like assert a := b.

  • gh-105487: Remove __copy__(), __deepcopy__() e __bases__ inexistentes das entradas __dir__() de types.GenericAlias.

  • gh-138192: Corrige a inicialização de contextvars para que todos os subinterpretadores recebam o valor MISSING.

  • gh-138479: Corrige uma falha quando __typing_subst__ de um objeto genérico retorna um objeto que não é uma tuple.

  • gh-138431: Fix a bug in the JIT optimizer when round-tripping strings and tuples.

  • gh-138378: Move the globals-to-const JIT optimizer pass into to the main JIT optimizer pass

Biblioteca

Núcleo e embutidos

  • gh-138372: Correção de SyntaxWarning emitido para subscrito expressão errôneo envolvendo literal de string template. Patch por Brian Schubert.

  • gh-138302: BINARY_OP now specializes to BINARY_OP_ADD_INT, BINARY_OP_SUBTRACT_INT or BINARY_OP_MULTIPLY_INT if operands are compact ints.

  • gh-138318: O REPL padrão agora evita destacar nomes embutidos (por exemplo, set ou format()) quando eles são usados como nomes de atributos (por exemplo, em value.set ou text.format).

  • gh-138349: Corrige falha em certos casos em que um módulo contém uma anotação de nível de módulo e uma compreensão.

  • gh-69605: Corrige alguns submódulos da biblioteca padrão ausentes no preenchimento automático de importações do REPL.

  • gh-61206: zipimport now supports zstandard compressed zip file entries.

Biblioteca

Núcleo e embutidos

  • gh-137838: Fix JIT trace buffer overrun by increasing possible exit stubs. Patch by Donghee Na.

  • gh-71679: Use the same quoting algorithm for the repr of bytearrays as for bytes objects and strings – use double quotes for quoting if the bytearray contains single quotes and does not contain double quotes.

  • gh-137384: Correção de uma falha ao usar o warnings módulo em um finalizador no desligamento. Patch por Kumar Aditya .

Biblioteca

  • gh-138004: Nas plataformas Solaris/Illumos, os nomes de threads agora são codificados como ASCII para evitar erros em sistemas (por exemplo, OpenIndiana) que não oferecem suporte a nomes não ASCII.

  • gh-137976: Removed localtime from the list of reported system timezones.

Núcleo e embutidos

  • gh-137992: Ensure that PyRefTracer_SetTracer() sync with all existing threads when called to avoid races in the free threaded build. Patch by Pablo Galindo

  • gh-137967: Show error suggestions on nested attribute access. Patch by Pablo Galindo

  • gh-137959: Replace the shim code added to every piece of jitted code with a single trampoline function.

  • gh-137883: Corrige recursão descontrolada ao chamar uma função com argumentos nomeados.

  • gh-137079: Correção do reconhecimento de erros de digitação em palavra reservada ao analisar arquivos. Patch por Pablo Galindo.

  • gh-137728: Corrige o tratamento de muitas variáveis locais pelo JIT. Isso anteriormente causava uma falha de segmentação.

  • gh-137716: Fix double period in AttributeError message for invalid mock assertions

  • gh-137433: Corrige um possível impasse na construção com threads livres quando threads do daemon habilitam ou desabilitam a criação de perfil ou rastreamento enquanto a thread principal está desligando o interpretador.

  • gh-137576: Correção para código-fonte incorreto exibido em tracebacks do REPL básico quando PYTHONSTARTUP é fornecido. Patch por Adam Hartz.

  • gh-37817: Allow assignment to __bases__ of direct subclasses of builtin classes.

  • gh-132732: Optimize _COMPARE_OP, _CONTAINS_OP, _UNARY_NEGATIVE, _UNARY_NOT, and _UNARY_INVERT in JIT builds with constant-loading uops (_POP_TWO_LOAD_CONST_INLINE_BORROW and _POP_TOP_LOAD_CONST_INLINE_BORROW), and then remove both to reduce instruction count.

  • gh-137400: Corrige uma falha na construção com threads livres ao desabilitar a criação de perfil ou o rastreamento em todos os threads com PyEval_SetProfileAllThreads() ou PyEval_SetTraceAllThreads() ou seus equivalentes em Python threading.settrace_all_threads() e threading.setprofile_all_threads().

  • gh-133143: Add sys.abi_info object to make ABI information more easily accessible.

  • gh-137400: Corrige uma falha na construção com threads livres ao desabilitar a criação de perfil ou o rastreamento em todos os threads com PyEval_SetProfileAllThreads() ou PyEval_SetTraceAllThreads() ou seus equivalentes em Python threading.settrace_all_threads() e threading.setprofile_all_threads().

  • gh-120037: Disable user site packages directory when a ._pth file is used, even if it contains import site.

  • gh-58124: Corrige erros de codificação Python em Unicode do codec da página de código: usar “cp65000” e “cp65001” em vez de “CP_UTF7” e “CP_UTF8”, que não são nomes de código Python válidos. Patch por Victor Stinner.

  • gh-136966: The object.__dict__ and __weakref__ descriptors now use a single descriptor instance per interpreter, shared across all types that need them. This speeds up class creation, and helps avoid reference cycles.

  • gh-137314: Corrigida uma regressão em que f-strings brutas interpretavam incorretamente sequências de escape em especificações de formato. As f-strings brutas agora preservam corretamente as contrabarras literais nas especificações de formato, correspondendo ao comportamento do Python 3.11. Por exemplo, rf"{obj:\xFF}" agora produz corretamente '\\xFF' em vez de 'ÿ'. Patch por Pablo Galindo.

  • gh-137308: Uma docstring independente no corpo de um nó é otimizada como uma instrução pass para garantir que o corpo do nó nunca fique vazio. Caso contrário, havia um ValueError em compile().

  • gh-137288: Corrige bug em que algumas instruções de bytecode de uma expressão booleana não estão associadas ao manipulador de exceção correto.

  • gh-137291: The perf profiler can now be used if a previous frame evaluation API has been provided.

  • gh-134291: Remove alguns usos mais recentes da API do macOS do compilador JIT para restaurar a compatibilidade com destinos de implantação mais antigos do OSX 10.15.

  • gh-88886: The codecs lookup function now again performs only minimal normalization of the encoding name before passing it to the search functions: all ASCII letters are converted to lower case, spaces are replaced with hyphens. This restores the pre-Python 3.9 behavior.

  • gh-131338: Desabilita verificações de limite de pilha computada em plataformas Linux não-glibc para corrigir travamentos em recursão profunda.

  • gh-136870: Corrige disputas de dados ao desinstrumentar o bytecode de objetos código executados simultaneamente em threads.

  • gh-132732: Optimize constant comparison for _COMPARE_OP_INT, _COMPARE_OP_FLOAT and _COMPARE_OP_STR in JIT builds

  • gh-127598: Improve ModuleNotFoundError by adding flavour text to the exception when the -S option is passed. Patch by Andrea Mattei.

  • gh-136801: Corrige o destaque de sintaxe do PyREPL em casos de correspondência após casos multilinhas. Contribuição de Olga Matoula.

  • gh-74185: The __repr__() of ImportError and ModuleNotFoundError now shows “name” and “path” as name=<name> and path=<path> if they were given as keyword arguments at construction time. Patch by Serhiy Storchaka, Oleg Iarygin, and Yoav Nir

Biblioteca

Núcleo e embutidos

Biblioteca

Núcleo e embutidos

  • gh-136541: Corrigimos alguns problemas com os trampolins do Perf em x86-64 e aarch64. Os trampolins não estavam sendo gerados corretamente em alguns casos, o que poderia fazer com que a integração do Perf não funcionasse corretamente. Patch por Pablo Galindo.

Biblioteca

Núcleo e embutidos

  • gh-136517: Corrigido um erro de digitação que impedia a exibição de objetos não colecionáveis quando o modo gc.DEBUG_UNCOLLECTABLE estava definido.

  • gh-136525: Corrige problema em que o bytecode por thread não era instrumentado para threads recém-criadas.

  • gh-132657: Melhora o desempenho de frozenset removendo travas na construção com threads livres.

  • gh-136459: Add support for perf trampoline on macOS, to allow profilers wit JIT map support to read Python calls. While profiling, PYTHONPERFSUPPORT=1 can be appended to enable the trampoline.

  • gh-132661: Interpolation.expression agora tem um padrão, a string vazia.

  • gh-132661: Reflete a recente mudança PEP 750.

    Não permite a concatenação de string.templatelib.Template e str. Também não permite a concatenação implícita de literais de t-string com strings e literais de f-strings.

  • gh-91636: Ao realizar a coleta de lixo, limpa as referências fracas (weakrefs) a objetos inacessíveis criados durante a execução dos finalizadores. Se essas referências fracas não forem limpas, elas podem revelar objetos inacessíveis.

  • gh-136355: Deprecate -b and -bb command line options and schedule them to become no-op in Python 3.17.

  • gh-109700: Corrige tratamento de erro de memória em PyDict_SetDefault().

  • gh-135552: Fix a bug caused by the garbage collector clearing weakrefs too early. The weakrefs in the tp_subclasses dictionary are needed in order to correctly invalidate type caches (for example, by calling PyType_Modified()). Clearing weakrefs before calling finalizers causes the caches to not be correctly invalidated. That can cause crashes since the caches can refer to invalid objects. Defer the clearing of weakrefs without callbacks until after finalizers are executed.

  • gh-136203: Improve TypeError error message, when richcomparing two types.MappingProxyType objects.

  • gh-136003: Fix threading.Thread objects becoming incorrectly daemon when created from an atexit callback or a pending call (Py_AddPendingCall()).

  • gh-78465: Corrige mensagem de erro para cls.__new__(cls, ...) onde cls não é um tipo de extensão ou embutido instanciável (com tp_new definido como NULL).

  • gh-135904: Perform more aggressive control-flow optimizations on the machine code templates emitted by the experimental JIT compiler.

  • gh-129958: Diferencia entre t-strings e f-strings em erros de sintaxe para novas linhas em especificadores de formato de strings interpoladas entre aspas simples.

  • gh-135871: Tentativas de trava de mutex não bloqueantes agora retornam imediatamente quando a trava está ocupado, em vez de girar brevemente na construção com threads livres.

  • gh-134584: Specialize POP_TOP in the JIT compiler by specializing for reference lifetime and type. This will also enable easier top of stack caching in the JIT compiler.

  • gh-135106: Restringe o mecanismo da lixeira aos objetos coletados pelo GC e cancele o rastreamento deles enquanto estiverem na lixeira para evitar conflitos entre os mecanismos do GC e da lixeira.

  • gh-135379: Changes specialization of BINARY_OP for ints to only specialize for “compact” ints. This streamlines the fast path at the cost of fewer specializations when very large integers are used.

  • gh-135607: Corrige possíveis corridas weakref no destrutor de um objeto na construção com threads livres.

  • gh-135608: Corrige uma falha no JIT envolvendo atributos de módulos.

  • gh-82088: Improve performance of PyLongObject conversion functions PyLong_AsLongAndOverflow(), PyLong_AsSsize_t(), PyLong_AsUnsignedLong(), PyLong_AsSize_t(), PyLong_AsUnsignedLongMask(), PyLong_AsUnsignedLongLongMask(), PyLong_AsLongLongAndOverflow() for integers larger than 2**30 up to 30%.

  • gh-135551: Sorting randomly ordered lists will often run a bit faster, thanks to a new scheme for picking minimum run lengths from Stefan Pochmann, which arranges for the merge tree to be as evenly balanced as is possible.

  • gh-135543: Emite o evento de auditoria sys.remote_exec quando sys.remote_exec() for chamado e migra remote_debugger_script para cpython.remote_debugger_script.

  • gh-135496: Corrige erro de digitação no tipo de conversão de f-strings (“exclamanation” -> “exclamation”).

  • gh-135474: Specialize integer operations only on compact integers. This is a CPython internal change.

  • gh-135371: Corrige as ferramentas de depuração asyncio para exibir corretamente as pilhas de chamadas de corrotinas internas juntamente com as dependências de tarefas externas. Os comandos python -m asyncio ps e python -m asyncio pstree agora mostram o contexto de execução completo. Patch por Pablo Galindo.

  • gh-135422: Fix regression in SyntaxError messages after gh-134036.

Biblioteca

  • gh-116738: Torna as funções em grp seguros para thread na construção com threads livres.

  • gh-127319: Define a variável de classe allow_reuse_port como False nos servidores XMLRPC, de registro e HTTP. Isso corresponde ao comportamento das versões anteriores do Python, que era não permitir a reutilização de portas.

Núcleo e embutidos

  • gh-130077: Gera corretamente erros de sintaxe personalizados quando for encontrada uma sintaxe incorreta contendo nomes que são prefixos de palavras reservadas contextuais. Patch por Pablo Galindo.

  • gh-131798: Optimize _CALL_LEN in the JIT when the length is known. Patch by Tomas Roun

  • gh-131798: Optimize _UNARY_NEGATIVE in JIT-compiled code.

  • gh-135148: Corrigido um bug em que expressões de depuração de strings f (usando =) removiam incorretamente partes de strings contendo aspas de escape e caracteres #. Patch por Pablo Galindo.

  • gh-131798: Optimize _UNARY_INVERT in JIT-compiled code.

  • gh-131798: Optimize away _CALL_TYPE_1 in the JIT when the return type is known. Patch by Tomas Roun

  • gh-133136: Limita o uso excessivo de memória na construção com threads livres quando um dicionário ou lista grande é redimensionado e acessado por várias threads.

  • gh-131798: Optimize _CHECK_METHOD_VERSION into _CHECK_FUNCTION_VERSION_INLINE in JIT-compiled code.

Biblioteca

Núcleo e embutidos

  • gh-134280: Desabilita a dobragem constante para ~ com um argumento booleano. Isso move o aviso de descontinuação do tempo de compilação para o tempo de execução.

  • gh-134876: Adiciona suporte à depuração remota PEP 768 para kernels Linux que não tenham CONFIG_CROSS_MEMORY_ATTACH configurado.

  • gh-134889: Corrige o tratamento de alguns opcodes que deixam operandos na pilha ao otimizar LOAD_FAST.

Biblioteca

Núcleo e embutidos

  • gh-117852: Fix argument checking of athrow().

  • gh-132617: Corrige verificação de modificação dict.update() que poderia levantar incorretamente um erro “dict mutated during update” quando um dicionário diferente era modificado e compartilhava o mesmo objeto de chaves subjacente.

  • gh-131798: Allow the JIT to remove unnecessary _ITER_CHECK_TUPLE ops.

  • gh-134679: Corrige falha no código QSBR da construção com threads livres que poderia ocorrer ao alterar o atributo __dict__ de um objeto.

  • gh-133912: Corrige a função da API C PyObject_GenericSetDict para manipular classes de extensão com valores embutidos.

  • gh-131798: Make the JIT optimizer understand that slicing a string/list/tuple returns the same type.

  • gh-134584: Add a reference count elimination pass to the JIT compiler. Patch by Ken Jin.

  • gh-131798: Optimize _POP_CALL_TWO_LOAD_CONST_INLINE_BORROW.

Biblioteca

Núcleo e embutidos

  • gh-127960: O shell interativo do PyREPL não inicia mais com os nomes globais __package__ e __file__ definidos como internos do pacote _pyrepl. Contribuição de Yuichiro Tachibana.

  • gh-130397: Remove o uso de maiúsculas e minúsculas especiais para os limites de profundidade da pilha C para WASI. Devido à proteção de pilha embutida do WebAssembly, isso não representa um problema de segurança.

  • gh-131798: JIT: replace _LOAD_SMALL_INT with _LOAD_CONST_INLINE_BORROW

  • gh-131798: Improve the JIT’s ability to optimize away cached class attribute and method loads.

  • gh-128066: Corrige um caso extremo em que o PyREPL levantava um erro incorretamente quando o Python era invocado em um sistema de arquivos somente leitura ao tentar gravar entradas no arquivo de histórico.

  • gh-131798: Improve the JIT’s ability to narrow unknown classes to constant values.

  • gh-134268: Add _POP_CALL_TWO_LOAD_CONST_INLINE_BORROW and use it to further optimize CALL_ISINSTANCE.

  • gh-131798: Split CALL_LIST_APPEND into several uops. Patch by Diego Russo.

  • gh-69605: Ao completar automaticamente uma importação no REPL, não encontrar candidatos agora não emite nenhuma sugestão, em vez de sugestões do espaço de nomes atual.

  • gh-134170: Add colorization to sys.unraisablehook() by default.

  • gh-91153: Corrige uma falha quando um bytearray é mutado simultaneamente durante a atribuição de item.

  • gh-134158: Corrige a coloração de chaves duplas em f-strings e t-strings no REPL.

  • gh-134119: Corrige falha ao chamar next() em um iterador de string template esgotado. Patch por Jelle Zijlstra.

  • gh-134100: Corrige um bug de uso após liberação que ocorre quando um módulo importado não está em sys.modules após sua importação inicial. Patch por Nico-Posada.

  • gh-134036: Improve SyntaxError message when using invalid raise statements.

  • gh-133999: Corrige regressão SyntaxError na análise de except após gh-123440.

  • gh-133886: Corrige sys.remote_exec() para caminhos não-ASCII em localidades não-UTF-8 e caminhos não-UTF-8 em localidades UTF-8.

  • gh-133400: Comportamento corrigido do Ctrl+D (^D) no módulo _pyrepl para corresponder ao comportamento antigo do REPL pré-3.13.

  • gh-133703: Corrige que a tabela de hash no dicionário pode ser maior do que o pretendido em algumas situações.

  • gh-133778: Corrige bug onde atribuir a atributos __annotations__ de classes definidas em from __future__ import annotations não tinham efeito.

  • gh-133711: Implement PEP 686: Enable Python UTF-8 Mode by default. Patch by Adam Turner.

  • gh-132762: fromkeys() não entra mais em laço infinito ao adicionar um pequeno conjunto de chaves a um dicionário base grande. Patch por Angela Liss.

  • gh-133541: Indentação inconsistente na entrada do usuário travava o novo REPL quando o realce de sintaxe estava ativo. Isso já foi corrigido.

  • gh-133516: Levanta ValueError quando as constantes True, False ou None forem usadas como um identificador após a normalização NFKC.

  • gh-131798: Allow the JIT to remove int guards after _GET_LEN by setting the return type to int.

  • gh-131798: Split CALL_ISINSTANCE into several uops, allowing the JIT to remove some of them.

  • gh-132554: Change iteration to use “virtual iterators” for sequences. Instead of creating an iterator, a tagged integer representing the next index is pushed to the stack above the iterable. For non-sequence iterators, NULL is pushed.

  • gh-130821: Enhance wrong type error messages and make them more consistent. Patch by Semyon Moroz.

  • gh-131798: Narrow the return type and constant-evaluate CALL_ISINSTANCE for a subset of known values in the JIT. Patch by Tomas Roun

  • gh-132542: Atualiza Thread.native_id após fork(2) para garantir a precisão. Patch por Noam Cohen.

Biblioteca

  • gh-132732: Automatically constant evaluate bytecode operations marked as pure in the JIT optimizer.

Núcleo e embutidos

  • gh-127971: Corrige leituras fora de um ponto além do final de uma string na pesquisa de string.

  • gh-132042: Improve class creation times by up to 12% by pre-computing type slots just once. Patch by Sergey Miryanov.

  • gh-133379: Correct usage of arguments in error messages.

  • gh-127266: In the free-threaded build, avoid data races caused by updating type slots or type flags after the type was initially created. For those (typically rare) cases, use the stop-the-world mechanism. Remove the use of atomics when reading or writing type flags. The use of atomics is not sufficient to avoid races (since flags are sometimes read without a lock and without atomics) and are no longer required.

  • gh-130425: Add "Did you mean: 'attr'?" suggestion when using del obj.attr if attr does not exist.

  • gh-128640: Corrige uma falha ao usar threads dentro de um subinterpretador.

Biblioteca

  • gh-116738: Make the module json safe to use under the free-threading build.

Núcleo e embutidos

  • gh-119494: Exception text when trying to delete attributes of types was clarified.

API C

Construção

  • gh-138489: Ao fazer compilação cruzada para WASI por build_wasm ou build_emscripten, a etapa build-details.json agora é incluída no processo de construção, assim como nas construções nativas.

    Isso corrige a tarefa libinstall que requer o arquivo build-details.json durante o processo.

  • gh-138497: The LLVM version used by the JIT at build time can now be modified using the LLVM_VERSION environment variable. Use this at your own risk, as there is only one officially supported LLVM version. For more information, please check Tools/jit/README.md.

  • gh-95952: When cross-compiling for WASI, require that the HOSTRUNNER environment variable be explicitly set.

    This was needed as macOS lacks the appropriate CLI tools to set a reasonable default.

  • gh-138061: Ensure reproducible builds by making JIT stencil header generation deterministic.

  • gh-128042: ./configure now warns when --enable-optimizations and CFLAGS=-O0 are both set, suggesting removing -O0 from CFLAGS for optimal performance. Patch by Taegyun Kim.

  • gh-132339: Adiciona suporte para OpenSSL 3.5.

  • gh-135621: O PyREPL não depende mais da biblioteca padrão curses. Contribuição de Łukasz Langa.

  • gh-135927: Fix building with MSVC when passing option /std:clatest.

  • gh-119132: Remove a tag “experimental” da construção com threads livres do CPython.

  • gh-135497: Corrige a detecção de MAXLOGNAME no script configure.ac.

  • gh-134923: As construções do Windows com otimização guiada por perfil habilitada agora usam /GENPROFILE e /USEPROFILE em vez das opções descontinuadas /LTCG:.

  • gh-134632: Corrigida a geração de build-details.json para usar INCLUDEPY, a fim de referenciar o subdiretório pythonX.Y do diretório include, conforme exigido em PEP 739, em vez do diretório include de nível superior.

  • gh-134486: The ctypes module now performs a more portable test for the definition of alloca(3), fixing a compilation failure on NetBSD.

  • gh-134455: Corrigida a geração de build-details.json para usar o c_api.headers correto, conforme definido em PEP 739, em vez de c_api.include.

  • gh-134273: Adiciona suporte para configurar sinalizadores do compilador para o JIT com CFLAGS_JIT

  • gh-115119: Removed implicit fallback to the bundled copy of the libmpdec library. Now this should be explicitly enabled via --with-system-libmpdec set to no or --without-system-libmpdec. Patch by Sergey B Kirpichev.

  • gh-131769: Corrige a detecção de quando a construção Python em uma construção cruzada é uma construção de pydebug.

  • gh-117088: O ligador AIX não oferece suporte à opção -h, portanto, evita-a por meio da verificação da plataforma

  • gh-123681: Verifica o comportamento de strftime() em tempo de execução, em vez de em tempo de compilação, para oferecer suporte à compilação cruzada. Remove a macro interna _Py_NORMALIZE_CENTURY.

  • gh-127545: Fix crash when building on Linux/m68k.

Python 3.14.0 beta 1

Data de lançamento: 2025-05-06

Windows

  • gh-132930: Marca o instalador para Windows como descontinuado e atualiza a documentação para abranger o novo gerenciador de instalação do Python.

  • gh-127405: Adiciona ABIFLAGS a sysconfig.get_config_vars() no Windows. Patch por Xuehai Pan.

Ferramentas/Demos

  • gh-130453: Permite a passagem de múltiplos argumentos nomeados com o mesmo nome de função em pygettext.

  • gh-130195: Adiciona mensagens de aviso quando a opção não implementada -a/--extract-all do pygettext for chamada.

Testes

  • gh-133131: O ambiente de testes do iOS agora selecionará o dispositivo “classe SE” lançado mais recentemente para testes, caso um dispositivo não seja especificado explicitamente.

  • gh-91048: Adiciona a capacidade de inspecionar externamente todas as tarefas asyncio pendentes, mesmo que nenhuma tarefa esteja inserida no laço de eventos.

  • gh-109981: O auxiliar de teste que conta a lista de descritores de arquivo abertos agora usa a abordagem otimizada /dev/fd em todas as plataformas Apple, não apenas no macOS. Isso evita travamentos causados por descritores de arquivo protegidos.

  • gh-132678: Adiciona --prioritize a -m test. Esta opção permite ao usuário especificar quais testes selecionados devem ser executados primeiro, mesmo que a ordem seja aleatória. Isso é particularmente útil para testes que demoram mais tempo para serem executados.

  • gh-131290: Os testes em Lib/test agora podem ser executados corretamente como scripts independentes.

Segurança

  • gh-115322: Os módulos de extensão subjacentes a readline:, subprocess e ctypes agora levantam eventos de auditoria em caminhos de código previamente descobertos, que podem levar ao acesso ao sistema de arquivos relacionado à chamada de função C e à execução de binários externos. O gancho de auditoria ctypes.call_function também foi corrigido para usar um valor sem sinal para seu function pointer.

Biblioteca

IDLE

  • gh-112936: corrige IDLE: nenhum item de menu Shell no modo de processo único.

Documentação

  • gh-107006: Move a documentação e o código de exemplo para threading.local da docstring para a documentação oficial.

  • gh-125142: Como parte do texto de introdução da ajuda embutida, mostre os atalhos de teclado para o novo REPL não básico (F1, F2 e F3).

Núcleo e embutidos

  • gh-133336: -J não está mais reservado para uso do Jython. Patch por Adam Turner.

  • gh-133261: Corrige um bug em que o ciclo GC não conseguia rastrear objetos na lixeira porque eles pareciam imortais. Quando objetos são adicionados à lixeira, tomamos cuidado para garantir que eles mantenham uma contagem de referências mortal.

  • gh-133346: Adicionado suporte experimental para temas de cores ao módulo _colorize.

  • gh-132917: Para a construção com threads livres, verifica o aumento no uso de memória do processo antes de acionar uma coleta de lixo automática completa. Se a memória usada não tiver aumentado 10% desde a última coleta, adia-a.

  • gh-91048: Adiciona uma nova interface de linha de comando python -m asyncio ps PID para inspecionar tarefas assíncronas em um processo Python em execução. Exibe uma tabela simples de relacionamentos de espera. Uma variante que mostra uma visualização em árvore também está disponível como python -m asyncio pstree PID. Ambas são úteis para depuração de código assíncrono. Patch por Pablo Galindo, Łukasz Langa, Yury Selivanov e Marta Gomez Macias.

  • gh-133304: Solução alternativa para a “canonização” do NaN em PyFloat_Pack4() e PyFloat_Unpack4() no RISC-V.

  • gh-133197: Melhora as mensagens de erro SyntaxError para prefixos de strings / bytes incompatíveis.

  • gh-133231: Adiciona novos utilitários de observação da compilação JIT: sys._jit.is_available(), sys._jit.is_enabled() e sys._jit.is_active().

Biblioteca

Núcleo e embutidos

  • gh-131798: Divide CALL_LEN em vários UOPs, permitindo que o JIT os remova durante a otimização. Patch por Diego Russo.

  • gh-131798: Usa sym_new_type em vez de sym_new_not_null para _BUILD_STRING, _BUILD_SET

  • gh-132942: Corrige duas corridas no cache de pesquisa de tipos. Isso afetava a construção com threads livres e podia causar travamentos (aparentemente bastante difíceis de acionar).

  • gh-131798: Propaga o tipo de retorno de _BINARY_OP_SUBSCR_TUPLE_INT em JIT. Patch por Tomas Roun

  • gh-132952: Acelera a inicialização com o argumento -S importando o módulo privado _io em vez de io. Isso corrige uma regressão de desempenho introduzida anteriormente no desenvolvimento do Python 3.14 e restaura o desempenho ao nível do Python 3.13.

  • gh-131798: Permite que o JIT remova as proteções int após _CALL_LEN definindo o tipo de retorno como int. Patch por Diego Russo

  • gh-131798: Divide CALL_TUPLE_1 em vários UOPs, permitindo que o JIT remova alguns deles. Patch por Tomas Roun

  • gh-131798: Divide CALL_STR_1 em vários UOPs, permitindo que o JIT remova alguns deles. Patch por Tomas Roun

  • gh-132825: Melhorias nas mensagens de erro de chaves/elementos não fragmentáveis para dict e set. Patch por Victor Stinner.

  • gh-131591: Redefine qualquer chamada pendente de depuração remota PEP 768 em filhos após chamadas os.fork().

  • gh-132713: Corrige a condição de corrida repr(list): mantém uma referência forte ao item ao chamar repr(item). Patch por Victor Stinner.

  • gh-132661: Implementa PEP 750 (Template Strings). Adiciona nova sintaxe para t-strings e implementa novos tipos internos string.templatelib.Template e string.templatelib.Interpolation.

  • gh-132479: Corrige travamento do compilador em determinadas circunstâncias em que várias anotações em nível de módulo incluem compreensões e outros escopos aninhados.

  • gh-132747: Corrige uma falha ao chamar __get__() de um method com um segundo argumento None.

  • gh-132744: Certas chamadas agora verificam a recursão descontrolada e respeitam o limite de recursão do sistema.

  • gh-132449: Erros de sintaxe que parecem erros de ortografia de palavra reservada do Python agora oferecem uma sugestão útil de correção. Contribuição de Pablo Galindo Salgado.

Biblioteca

  • gh-132737: Suporte a código de criação de perfil que requer __main__, como pickle.

Núcleo e embutidos

  • gh-132639: Adicionadas PyLong_AsNativeBytes(), PyLong_FromNativeBytes() e PyLong_FromUnsignedNativeBytes() à API C limitada.

  • gh-100239: Adiciona especialização para BINARY_OP/SUBSCR na lista e no fatiamento.

  • gh-132508: Utiliza inteiros marcados na pilha de avaliação para representar os deslocamentos de instrução ao levantar novamente uma exceção. Isso evita a necessidade de encapsular o inteiro, o que poderia falhar em condições de pouca memória.

  • gh-124476: Corrige decodificação da codificação local no local C.UTF-8.

  • gh-131927: Avisos do compilador originados do mesmo módulo e número de linha agora são emitidos apenas uma vez, correspondendo ao comportamento dos avisos emitidos pelo código do usuário. Isso também pode ser configurado com filtros warnings.

  • gh-132457: Torna staticmethod() e classmethod() genéricos.

  • gh-131798: Usa sym_new_type em vez de sym_new_not_null para _BUILD_LIST, _BUILD_SET, _BUILD_MAP

  • gh-131798: Divide CALL_TYPE_1 em vários uops, permitindo que o JIT remova alguns deles.

  • gh-132386: Corrige falha ao passar uma subclasse dict como parâmetro globals para exec().

  • gh-127682: Não é mais necessário chamar __iter__ duas vezes ao criar e executar uma expressão geradora. A criação de uma expressão geradora a partir de uma expressão não iterável só será levantada quando a expressão geradora for executada. Isso alinha o comportamento das expressões geradoras com outros geradores.

  • gh-132261: O armazenamento interno para anotações e funções de anotação em classes agora usa chaves diferentes no dicionário de classes. Isso elimina vários casos extremos em que o acesso aos atributos __annotate__ e __annotations__ se comportaria de forma imprevisível.

  • gh-132284: Não envolve slots base PyCFunction na criação da classe se não forem substituídos.

  • gh-130415: Melhora a capacidade do JIT de remover cargas constantes e variáveis locais não utilizadas e corrige um problema em que a desalocação de valores não utilizados poderia fazer com que o código JIT travasse ou se comportasse incorretamente.

  • gh-126703: Corrige possível uso após free em casos em que a definição de um método tem o mesmo tempo de vida que seu self.

  • gh-132286: Corrige que type.__annotate__ não foi excluído quando type.__annotations__ foi excluído.

  • gh-131798: Permite que o JIT remova uma instrução extra _TO_BOOL_BOOL após _CONTAINS_OP_DICT definindo o tipo de retorno como bool.

  • gh-124715: Evita estouros de pilha ao chamar Py_DECREF(). Objetos de extensão de terceiros não precisam mais usar o mecanismo de “lixeira”, pois a proteção agora está incorporada à macro Py_DECREF().

  • gh-131798: Permite que o compilador JIT remova algumas verificações de tipo para operações em listas, tuplas, dicionários e conjuntos.

  • gh-128398: Melhoria na mensagem de erro quando um objeto que ofereça suporte ao protocolo de gerenciador de contexto síncrono (ou assíncrono) é inserido usando async with (ou seja, with) em vez de with (ou seja, async with). Patch por Bénédikt Tran.

  • gh-131798: Permite que o JIT remova as proteções Unicode após _BINARY_OP_SUBSCR_STR_INT definindo o tipo de retorno como string.

  • gh-131878: Trata exceções não capturadas no laço de entrada principal para o novo REPL.

  • gh-131878: Corrige suporte a caracteres Unicode com dois ou mais pontos de código no Windows no novo REPL.

  • gh-126835: Move a dobragem de constante para o otimizador de olho mágico. Renomeia os arquivos relacionados à otimização AST (Python/ast_opt.c -> Python/ast_preprocess.c), structs (_PyASTOptimizeState -> _PyASTPreprocessState) e funções (_PyAST_Optimize -> _PyAST_Preprocess, _PyCompile_AstOptimize -> _PyCompile_AstPreprocess).

  • gh-114809: Adiciona suporte para construções multiarquitetura do macOS com o JIT habilitado

  • gh-131507: O PyREPL agora oferece suporte a realce de sintaxe. Contribuição de Łukasz Langa.

  • gh-130907: Se as __annotations__ de um objeto de módulo forem acessadas enquanto o módulo estiver em execução, retorne as anotações que foram definidas até agora, sem armazená-las em cache.

  • gh-130104: pow() de três argumentos agora tenta chamar __rpow__() se necessário. Anteriormente, ele só era chamado em pow() de dois argumentos e no operador binário de potência.

  • gh-130070: Corrigido um erro de asserção para exec() passando uma string source e uma closure não None. Patch por Bartosz Sławecki.

  • gh-129958: Corrige um bug que permitia quebras de linha inconsistentes em especificadores de formato para f-strings entre aspas simples. Patch por Pablo Galindo.

  • gh-129858: instruções elif que seguem um bloco else agora têm uma mensagem de erro específica.

  • gh-69605: Adiciona o módulo autocomplete ao PyREPL.

  • gh-128555: Adiciona o sinalizador sys.flags.thread_inherit_context.

  • gh-123539: Melhora a mensagem SyntaxError para usar import ... as e from ... import ... as sem um nome.

  • gh-102567: -X importtime agora aceita o valor 2, que indica que uma entrada importtime também deve ser impressa se um módulo importado já tiver sido carregado. Patch por Noah Kim e Adam Turner.

  • gh-116436: Melhora a mensagem de erro quando TypeError ocorre durante dict.update()

  • gh-103997: String arguments passed to “-c” are now automatically dedented. This allows “python -c” invocations to be indented in shell scripts without causing indentation errors. (Patch by Jon Crall and Steven Sun)

Biblioteca

  • gh-89562: Remove o membro hostflags da struct PySSLContext.

API C

  • gh-133166: Corrige regressão onde PyType_GetModuleByDef() retorna NULL sem definir TypeError quando um tipo estático é passado.

  • gh-133164: Adicionada a função PyUnstable_Object_IsUniqueReferencedTemporary() para determinar se um objeto existe como uma variável temporária única na pilha do interpretador. Esta função substitui alguns casos em que verificar se Py_REFCNT() é uma variável temporária não é mais suficiente para determinar se é seguro modificar um objeto Python no local sem efeitos colaterais visíveis.

  • gh-133140: Adiciona PyUnstable_Object_IsUniquelyReferenced() como um substituto para Py_REFNCT(op) == 1 em construções com threads livres do Python.

  • gh-131747: Em plataformas não Windows, descontinua o uso de ctypes.Structure._pack_ para usar um layout compatível com o Windows. O layout deve ser especificado explicitamente definindo ctypes.Structure._layout_ como 'ms'.

  • gh-128972: Para construções sem threads livres, o layout de memória de PyASCIIObject é revertido para corresponder ao Python 3.13. (Observe que a estrutura não faz parte da ABI estável e, portanto, seu layout de memória tem garantia de estabilidade.)

  • gh-133079: As APIs não documentadas Py_C_RECURSION_LIMIT e PyThreadState.c_recursion_remaining, adicionadas na versão 3.13, foram removidas sem um período de descontinuação.

  • gh-132987: Os formatos k e K em PyArg_Parse() agora oferecem suporte ao método especial __index__(), como todos os outros formatos inteiros.

  • gh-132909: Corrige um estouro ao manipular o formato K em Py_BuildValue(). Patch por Bénédikt Tran.

  • gh-132798: As funções descontinuadas e não documentadas PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(), PyUnicode_AsEncodedUnicode() e PyUnicode_AsDecodedUnicode() estão programadas para remoção na versão 3.15.

  • gh-132470: Cria um ctypes.CField com um byte_size que não corresponde ao tamanho do tipo real agora levanta um ValueError em vez de travar o interpretador.

  • gh-112068: [Revertido em gh-136991] Adicionado suporte a argumentos anuláveis em PyArg_Parse() e funções similares. Adicionar ? após qualquer unidade de formato faz com que None seja aceito como valor.

  • gh-50333: Sequências não-tuplas estão descontinuadas como argumento para a unidade de formato (items) em PyArg_ParseTuple() e outras funções de análise de argumentos se items contiver unidades de formato que armazenam um buffer emprestado ou uma referência emprestada.

Construção

  • gh-113464: Use o repositório “externals” cpython-bin-deps para o gerenciamento de dependências do Windows LLVM. A instalação manual do LLVM não é mais necessária para construções JIT do Windows.

  • gh-133183: Os shims do compilador iOS agora incluem IPHONEOS_DEPLOYMENT_TARGET em triplos de destino, garantindo que os mínimos da versão do SDK sejam respeitados.

  • gh-133167: Corrige o processo de compilação com --enable-optimizations e --without-docstrings.

  • gh-133171: Como as construções com threads livres não oferecem suporte ao compilador JIT experimental, evita que essas configurações sejam combinadas.

  • gh-132758: Corrige construção com interpretador de chamada de cauda e pystats.

  • gh-132649: O script PClayout agora permite passar --include-tcltk no Windows ARM64.

  • gh-132257: Altera os sinalizadores LTO padrão no GCC para não passar -flto-partition=none e permitir a paralelização de LTO. Para versões GNU mais recentes e GCC, isso representa um aumento de velocidade múltiplo nos tempos de construção com LTO, sem perda perceptível de desempenho.

  • gh-132026: Corrige o uso de identificadores indefinidos na detecção de tripletos de plataforma em plataformas MIPS Linux.

Python 3.14.0 alpha 7

Data de lançamento: 2025-04-08

macOS

  • gh-124111: Atualiza o instalador do macOS para usar o Tcl/Tk 8.6.16.

  • gh-131423: Atualiza o instalador do macOS para usar o OpenSSL 3.0.16. Patch por Bénédikt Tran.

  • gh-131025: Atualiza o instalador do macOS para ser fornecido com o SQLite 3.49.1.

Windows

  • gh-131423: Atualiza a versão empacotada do OpenSSL para 3.0.16. A nova construção também desabilita o suporte a uplink, o que pode ser relevante para incorporadores, mas não tem impacto no uso normal.

  • gh-131453: Algumas constantes SND_* e MB_* foram adicionadas ao winsound.

  • gh-91349: Substitui nossa cópia de zlib por zlib-ng, para melhorias de desempenho em zlib.

  • gh-131025: Atualiza o instalador do Windows para ser fornecido com o SQLite 3.49.1.

Ferramentas/Demos

  • gh-132121: Sempre escapa caracteres Unicode não imprimíveis em pygettext.

  • gh-131852: msgfmt não adiciona mais POT-Creation-Date aos arquivos .mo gerados para consistência com GNU msgfmt.

Testes

  • gh-131277: Permite remover a configuração de uma ou mais variáveis de ambiente simultaneamente via EnvironmentVarGuard.unset(). Patch por Bénédikt Tran.

  • gh-131050: test_ssl.test_dh_params é ignorado se a biblioteca TLS subjacente não oferecer suporte a Diffie-Hellman efêmero de campo finito.

Segurança

  • gh-131809: Atualiza libexpat empacotado para 2.7.1

  • gh-131261: Atualiza para libexpat 2.7.0

  • gh-121284: Corrige bug na dobragem (folding) de palavras codificadas do rfc2047 ao achatar uma mensagem de e-mail usando uma política de e-mail moderna. Anteriormente, quando uma palavra codificada era muito longa para uma linha, ela era decodificada, dividida em linhas e recodificada. Mas vírgulas e outros caracteres especiais no texto original podiam ser deixados sem codificação e sem aspas. Isso poderia teoricamente ser usado para falsificar linhas de cabeçalho usando uma palavra codificada cuidadosamente construída se o e-mail renderizado resultante fosse transmitido ou reanalisado.

Biblioteca

Documentação

Núcleo e embutidos

  • gh-131798: Permite que o JIT remova uma instrução extra _TO_BOOL_BOOL após _CONTAINS_OP_SET definindo o tipo de retorno como bool.

  • gh-132011: Corrige falha ao chamar list.append() como um método não vinculado.

  • gh-131998: Corrige uma falha ao usar um objeto de método não vinculado descritor em uma função onde um descritor de método vinculado foi usado.

  • gh-131591: Implementa a PEP 768 (interface de depuração externa segura para CPython). Adiciona uma nova função sys.remote_exec() ao módulo sys. Esta função agenda a execução de um arquivo Python em um processo separado. Patch por Pablo Galindo, Matt Wozniski e Ivona Stojanovic.

  • gh-131798: Permite que o JIT omita a proteção str no teste de veracidade quando o tipo str for conhecido.

  • gh-131833: Adiciona suporte para a remoção opcional de parênteses de agrupamento ao usar vários tipos de exceção, conforme a PEP 758. Patch por Pablo Galindo.

  • gh-130924: O uso de um nome em uma anotação de escopo de função não aciona mais a criação de uma célula para essa variável. Isso corrige uma regressão em versões alfa anteriores do Python 3.14.

  • gh-131800: Melhora a capacidade do JIT experimental de remover verificações de tipo para determinadas operações de subscrição.

  • gh-131738: O compilador emite código otimizado para chamadas any/all/tuple embutidas sobre uma expressão geradora.

  • gh-131719: Corrige a falta de verificação de NULL em _PyMem_FreeDelayed na construção com threads livres.

  • gh-131670: Corrige falha em anext() na sincronização __anext__() levantando uma exceção.

  • gh-131666: Correção da assinatura dos objetos anext_awaitable.close. Patch por Bénédikt Tran.

  • gh-130415: Otimiza a comparação de duas constantes em construções JIT

  • gh-129149: Adiciona um atalho para inteiros pequenos e médios em PyLong_FromInt32(), PyLong_FromUInt32(), PyLong_FromInt64() e PyLong_FromUInt64(). Patch por Chris Eibl.

  • gh-130887: Otimiza a geração de código AArch64 para o JIT. Patch por Diego Russo

  • gh-130956: Otimiza a geração de código AArch64 para o JIT. Patch por Diego Russo

  • gh-130928: Corrige mensagem de erro ao formatar bytes usando o sinalizador 'i'. Patch por Maxim Ageev.

  • gh-130935: Anotações em nível de classe e módulo definidas condicionalmente agora só são refletidas em __annotations__ se o bloco em que se encontram for executado. Patch por Jelle Zijlstra.

  • gh-130775: Não falha em column negativo e end_column em locais ast.

  • gh-130704: Otimize LOAD_FAST e sua forma de superinstrução para reduzir a sobrecarga na contagem de referências. Essas instruções são substituídas por variantes mais rápidas que carregam referências emprestadas na pilha de operandos quando podemos provar que a referência no quadro sobrevive à referência carregada na pilha.

  • gh-88887: Corrigindo vazamento do processo de multiprocessamento Resource Tracker, geralmente observado ao executar Python como PID 1.

  • gh-130115: Corrige um problema com identificadores de thread sendo estendidos por sinal em algumas plataformas.

Biblioteca

  • gh-99108: Adiciona suporte para implementação embutida de HMAC (RFC 2104) com base em HACL*. Patch por Bénédikt Tran.

Núcleo e embutidos

  • gh-130080: Implementa a PEP 765: Não permitir return/break/continue que saiam de um bloco finally.

  • gh-129900: Corrige códigos de retorno dentro de SystemExit que não estão sendo retornados pelo REPL.

  • gh-128632: Não mais permite __classdict__ como nome de um parâmetro de tipo. Usar esse nome anteriormente travava o interpretador em algumas circunstâncias.

  • gh-126703: Melhora o desempenho dos métodos embutidos usando uma freelist.

  • gh-126703: Melhora o desempenho de range usando uma freelist.

API C

  • gh-131740: Atualiza PyUnstable_GC_VisitObjects para percorrer a geração permanente.

  • gh-131525: O PyTupleObject agora armazena em cache o valor de hash calculado no novo campo ob_hash.

Construção

  • gh-131865: A construção do DTrace agora passa corretamente as variáveis CC e CFLAGS para o comando dtrace ao utilizar o SystemTap no Linux.

  • gh-131675: Corrige construções da biblioteca mimalloc para alvos ARM de 32 bits.

  • gh-131691: O clang-cl no Windows precisa da opção /EHa para oferecer suporte a SEH (gerenciamento de exceções estruturadas) corretamente. Correção por Chris Eibl.

  • gh-131278: Adiciona o sinalizador de otimização WITH_COMPUTED_GOTOS às construções do Windows para quando usar um compilador compatível (atualmente clang-cl). Patch por Chris Eibl.

  • gh-130213: Atualiza a biblioteca HACL* fornecida para corrigir problemas de construção com compiladores clang mais antigos.

  • gh-130673: Corrige possível erro KeyError ao manipular seções de objetos durante o processo de construção JIT.

Python 3.14.0 alpha 6

Data de lançamento: 2025-03-14

macOS

Windows

  • gh-131020: pylauncher detecta corretamente um BOM ao procurar pelo shebang. Correção por Chris Eibl.

Ferramentas/Demos

  • gh-130453: Torna possível substituir palavra reservada padrão em pygettext.

  • gh-85012: Redefine corretamente msgctxt ao compilar mensagens em msgfmt.

  • gh-130453: Estende o suporte para especificar palavras reservadas personalizadas em pygettext.

  • gh-130195: Adiciona mensagens de aviso quando a opção -a/--extract-all não implementada pygettext for chamada.

  • gh-130057: Adiciona suporte para comentários do tradutor em pygettext.py.

  • gh-130025: O ambiente de teste do iOS agora manipula corretamente links simbólicos usados como referências de framework Python.

  • gh-129911: Corrige a entrada de palavra reservada na saída de ajuda de pygettext.

Testes

  • gh-129200: Agora, vários executores do ambiente de testes do iOS podem ser iniciados ao mesmo tempo sem gerar ambiguidade sobre a propriedade do simulador.

  • gh-130292: O banco de testes do iOS agora será executado com sucesso em uma máquina que não executou testes do Xcode anteriormente (como configurações de CI).

  • gh-130293: Os testes de colorização terminal não são mais sensíveis ao valor da variável TERM no ambiente de teste.

  • gh-129401: Corrige um teste instável em test_repr_rlock que verifica a representação de multiprocessing.RLock.

  • gh-126332: Adiciona testes de unidade para pyrepl.

Segurança

  • gh-127371: Evita buffering ilimitado para tempfile.SpooledTemporaryFile.writelines(). Anteriormente, o spillover de disco era verificado somente após o iterador de linhas ter sido esgotado. Agora, isso é feito após cada linha ser escrita.

Biblioteca

  • gh-131204: Usa a fonte monoespaçada do System Font Stack para suporte multiplataforma em difflib.HtmlDiff.

  • gh-131196: Melhora o desempenho de uuid.UUID.hex e uuid.UUID.__str__.

  • gh-130940: O comportamento de PyConfig.use_system_logger foi modificado para ser habilitado por padrão no iOS. Ele permanece desabilitado por padrão no macOS.

  • gh-131123: Complementações suportadas para atributos de variáveis de conveniência em pdb.

  • gh-93096: Removida CLI não documentado python -m difflib. Em vez disso, use python -m doctest Lib/difflib.py -v. Patch por Semyon Moroz.

  • gh-93096: Removidos os argumentos não documentados -t e -v de python -m pickle. Use python -m doctest Lib/pickle.py -v em seu lugar. Patch por Semyon Moroz.

  • gh-81267: Corrige a mensagem de erro time.sleep() quando um objeto que não pode ser interpretado como um inteiro ou float é fornecido.

  • gh-93096: Removidos os argumentos não documentados -t e -v de python -m pickletools. Em vez disso, use python -m doctest Lib/pickletools.py -v. Patch por Semyon Moroz.

  • gh-131045: Corrige problema com __contains__, valores e pseudomembros para enum.Flag.

  • gh-130959: Corrige implementação puro Python de datetime.time.fromisoformat() para rejeitar horários com espaços na parte fracionária (por exemplo, 12:34:56.400 +02:00), correspondendo à implementação C. Patch por Michał Gorny.

  • gh-130806: Exclui gzip.GzipFile antes de ser fechado agora emite uma ResourceWarning.

  • gh-130637: Adiciona validação para dados de resposta numérica no método poplib.POP3.stat()

  • gh-130665: Aplica somente a localidade à CLI calendar quando definido via --locale e não via variável de ambiente LANG.

  • gh-130660: sys.ps1 e sys.ps2 agora são restaurados após a chamada code.interact().

  • gh-130608: Remove o argumento dirs_exist_ok de pathlib.Path.copy() e copy_into(). Esses métodos são novos no Python 3.14.

  • gh-130461: Remove as diretivas .. index:: da documentação do módulo uuid. Essas diretivas criavam entradas no índice geral para getnode(), bem como para as funções construtoras uuid1(), uuid3(), uuid4(), uuid5() e uuid8().

  • gh-130379: O módulo zipapp agora calcula a lista de arquivos a serem adicionados ao arquivo antes de criá-lo. Isso evita incluir acidentalmente o alvo quando ele está sendo criado no diretório de origem.

  • gh-82987: Pontos de interrupção em linha como breakpoint() ou pdb.set_trace() sempre interromperão o programa ao chamar o quadro, ignorando o padrão skip (se houver).

  • gh-125377: <tab> no início da linha em pdb a entrada multilinha preencherá uma indentação de 4 espaços agora, em vez de inserir um caractere \t.

  • gh-125413: Certifica-se de que o caminho retornado de pathlib.Path.copy() ou move() tenha info atualizado.

  • gh-65697: O configparser do stdlib agora tentará validar se as chaves que ele grava não resultarão em corrupção de arquivo (criando um arquivo que não poderá ser analisado com precisão por uma futura chamada read() do mesmo analisador sintático). Tentar corromper o comando write() levantará uma InvalidWriteError.

  • gh-125413: Acelera Path.copy fazendo melhor uso de info internamente.

  • gh-130285: Corrige casos extremos para random.sample() permitindo que o parâmetro counts especifique uma população vazia. Então agora, sample([], 0, counts=[]) e sample('abc', k=0, counts=[0, 0, 0]) ambos dão o mesmo resultado que sample([], 0).

  • gh-124703: Executa o comando quit em pdb levantará bdb.BdbQuit quando pdb for iniciado em um console interativo usando breakpoint() ou pdb.set_trace().

  • gh-107773: Torna a subclasse datetime __repr__() consistente em ambas as implementações. Patch por Semyon Moroz.

  • gh-130250: Corrige uma regressão em traceback.print_last().

  • gh-123471: Torna as iterações simultâneas sobre itertools.batched seguras sob threads livres.

  • gh-57537: Suporte a pontos de interrupção para módulos zipimport em pdb

  • gh-130230: Corrige falha em pow() com apenas Decimal terceiro argumento.

  • gh-126944: Mostra erros explícitos quando os argumentos obrigatórios dos comandos pdb estiverem faltando

  • gh-127750: Melhora a representação dos métodos e descritores functools.singledispatchmethod.

  • gh-128520: Aplica conversão de tipo consistentemente nos métodos pathlib.PurePath e Path pode aceitar um objeto de caminho como argumento, como match() e rename(). O argumento agora é convertido em objeto de caminho se não possuir o atributo with_segments(), e não em caso contrário.

  • gh-118761: Reverte uma alteração na versão anterior, tentando tornar preguiçosas algumas importações stdlib usadas no módulo subprocess, pois isso estava causando erros durante os finalizadores __del__ que chamavam métodos como terminate, kill ou send_signal.

  • gh-130164: Corrigia uma falha ao levantar TypeError em inspect.Signature.bind() para argumentos somente posicionais fornecidos como nomeados quando um argumento nomeado variável (por exemplo, **kwargs) está presente.

  • gh-130151: Corrigir vazamentos de referência em _hashlib.hmac_new() e _hashlib.hmac_digest(). Patch por Bénédikt Tran.

  • gh-130145: Corrige asyncio.AbstractEventloop.run_forever() quando outro laço já estiver em execução.

  • gh-130139: Corrige bug onde ast.parse() não gerava erro na entrada AST que não era do tipo correto, quando chamado com optimize=False.

  • gh-127260: Proibição do uso de dois pontos (“:”) como separador de componentes fracionários e outras melhorias na consistência de levantar erros entre as implementações em C e Python de datetime.time.fromisoformat() e datetime.datetime.fromisoformat(). Patch por Semyon Moroz.

  • gh-85795: O uso de super() e __class__ variável de clausura em métodos definidos pelo usuário das subclasses typing.NamedTuple agora é explicitamente proibido em tempo de execução. Contribuição de Bartosz Sławecki em gh-130082.

  • gh-118761: Melhora o tempo de importação de cmd importando lentamente inspect e removendo string. Patch por Semyon Moroz.

  • gh-129726: Corrige gzip.GzipFile levantando uma exceção não levantável durante a coleta de lixo ao fazer referência a um objeto temporário, interrompendo o laço de referências com weakref.

  • gh-127750: Remove o armazenamento em cache quebrado functools.singledispatchmethod() introduzido em gh-85160. Obtém o mesmo desempenho usando otimizações diferentes.

  • gh-129948: Adiciona suporte para set compartilhado para multiprocessing.managers.SyncManager via SyncManager.set().

  • gh-129965: Atualização dos tipos MIME para .avi e .wav. Adição dos tipos MIME para .docx, .pptx, .xlsx, .epub, .flac, .m4a, .odg, .odp, .ods, .odt, .oga, .ogg, .ogx e .weba. Patch por Hugo van Kemenade.

  • gh-129889: Suporte ao protocolo do gerenciador de contexto por contextvars.Token. Patch por Andrew Svetlov.

  • gh-97850: Update the deprecation warning of importlib.abc.Loader.load_module.

  • gh-129678: configparser.ConfigParser: não escreve uma seção vazia sem nome

  • gh-128641: Restaura o desempenho de configparser.ConfigParser.read().

  • gh-129569: Corrige unicodedata.normalize() para sempre retornar um objeto embutido str quando receber uma entrada de uma subclasse str, independentemente de a string já estar normalizada.

  • gh-128231: A execução de múltiplas instruções no novo REPL agora para imediatamente após a primeira exceção encontrada. Patch por Bartosz Sławecki.

  • gh-96092: Corrige um bug em traceback.walk_stack() chamado com None, que estava pulando mais quadros do que nas versões anteriores. Esta correção de bug também altera o walk_stack para percorrer a pilha no quadro em que foi chamado, em vez de onde foi usado pela primeira vez.

  • gh-129288: Adiciona os campos opcionais l2_cid e l2_bdaddr_type à tupla sockaddr socket BTPROTO_L2CAP.

  • gh-128703: Corrige mimetypes.guess_type() para usar o mapeamento padrão para Content-Type vazio no registro.

  • gh-128647: Escreve rapidamente nos buffers passados para as implementações readinto() e readinto1() de gzip.GzipFile, evitando alocações desnecessárias. Patch por Chris Markiewicz.

  • gh-128184: Melhoria na exibição do objeto annotationlib.ForwardRef dentro das representações inspect.Signature. Isso também corrige uma NameError levantada ao usar dataclasses.dataclass() em classes com referências futuras não resolvíveis.

  • gh-128041: Adiciona concurrent.futures.ProcessPoolExecutor.terminate_workers() e concurrent.futures.ProcessPoolExecutor.kill_workers() como formas de encerrar ou eliminar todos os processos de trabalho ativos no pool fornecido. (Contribuição de Charles Machalow em gh-130849.)

  • gh-127647: Adiciona os protocolos io.Reader e io.Writer como alternativas para typing.IO, typing.TextIO e typing.BinaryIO.

  • gh-109798: Adicionadas informações adicionais às mensagens de erro em datetime e tornando as mensagens mais consistentes entre as implementações em C e Python. Patch por Semyon Moroz.

  • gh-125746: Delay deprecated zipimport.zipimporter.load_module() removal time to 3.15. Use zipimport.zipimporter.exec_module() instead.

  • gh-74028: Adiciona o parâmetro opcional buffersize a concurrent.futures.Executor.map() para limitar o número de tarefas enviadas cujos resultados ainda não foram produzidos. Se o buffer estiver cheio, a iteração sobre os iteráveis será pausada até que um resultado seja produzido pelo buffer.

  • gh-124927: Caracteres não imprimíveis agora são manipulados corretamente no novo REPL.

  • gh-124096: Ativa o modo de terminal virtual e habilita a colagem entre colchetes no REPL no console do Windows. (Se o terminal não oferecer suporte à colagem entre colchetes, habilitá-la não fará nada.)

  • gh-89083: Adiciona uuid.uuid7() para gerar objetos UUIDv7, conforme especificado em RFC 9562. Patch por Bénédikt Tran.

  • gh-89083: Adiciona uuid.uuid6() para gerar objetos UUIDv6, conforme especificado em RFC 9562. Patch por Bénédikt Tran.

  • gh-117151: Aumenta io.DEFAULT_BUFFER_SIZE de 8k para 128k e ajusta open() em plataformas onde os.fstat() fornece um campo st_blksize (como Linux) para usar max(min(blocksize, 8 MiB), io.DEFAULT_BUFFER_SIZE) em vez de sempre usar o tamanho do bloco do dispositivo. Isso deve melhorar o desempenho de E/S. Patch por Romain Morotti.

  • gh-105499: Transforma types.UnionType em um apelido para typing.Union. Tanto int | str quanto Union[int, str] agora criam instâncias do mesmo tipo. Patch por Jelle Zijlstra.

  • gh-93096: Documenta a linha de comando para mimetypes. Agora, ele sai com 1 em caso de falha, em vez de 0, e 2 em caso de parâmetros de linha de comando incorretos, em vez de 1. Além disso, os erros são exibidos em stderr em vez de stdout, e seu texto ficou mais conciso. Patch por Oleg Iarygin e Hugo van Kemenade.

Documentação

Núcleo e embutidos

  • gh-131141: Corrige disputa de dados na instrumentação sys.monitoring ao registrar retorno de chamada.

  • gh-130804: Corrige suporte a caracteres Unicode no Windows no novo REPL.

  • gh-130932: Corrige tratamento de exceção incorreto em _PyModule_IsPossiblyShadowing

  • gh-122029: sys.setprofile() e sys.settrace() não gerarão um evento c_call para INSTRUMENTED_CALL_FUNCTION_EX se o método chamável for um método com uma função C encapsulada, porque não geramos um evento c_return nesse caso.

  • gh-129964: Corrige travamento do JIT no Windows no Arm. Patch por Diego Russo e Brandt Bucher.

  • gh-130851: Corrige uma falha na construção com threads livres ao construir um objeto code com co_consts que contém instâncias de tipos que não são gerados pelo compilador de bytecode.

  • gh-128534: Certifica-se de que os ramos esquerdo e direito tenham a mesma origem para laços async for. Adicione esses ramos ao iterador co_branches().

  • gh-130794: Corrige vazamento de memória na construção com threads livres ao redimensionar uma lista ou dicionário compartilhado de vários threads de curta duração.

  • gh-130415: Melhora a compreensão do JIT de números inteiros em contexto booleano.

  • gh-130382: Corrige PyRefTracer_DESTROY não sendo enviado de Py_DECREF() de Python/ceval.c

  • gh-130574: Renumera RESUME de 149 para 128.

  • gh-124878: Corrige condições de corrida durante a finalização do tempo de execução que poderiam levar ao acesso à memória liberada.

  • gh-130415: Melhora a capacidade do JIT experimental de restringir valores booleanos com base nos resultados de testes de veracidade.

  • gh-130618: Corrige um bug que estava causando o levantamento de UnicodeDecodeError ou SystemError ao usar f-strings com expressões lambda com caracteres não-ASCII. Patch por Pablo Galindo

  • gh-123044: Certifica-se de que a localização dos alvos de ramificação nos casos match esteja no corpo, não no padrão.

  • gh-128534: Adiciona monitoramento de ramificação (eventos BRANCH_LEFT e BRANCH_RIGHT) para laços async for.

  • gh-130163: Corrige possíveis travamentos relacionados à alteração simultânea e ao uso dos atributos do módulo sys.

  • gh-122029: INSTRUMENTED_CALL_KW expandirá o método antes do monitoramento para refletir o comportamento real com mais precisão.

  • gh-130415: Melhora a capacidade do JIT de otimizar strings em contextos booleanos.

  • gh-130396: Usa limites de pilha reais (de pthread_getattr_np(3)) para Linux e outros sistemas com _GNU_SOURCE definido ao determinar limites para proteção de pilha C.

  • gh-128396: Corrige uma falha que ocorre ao chamar locals() dentro de uma compreensão em linha que usa a mesma variável local que o escopo do quadro externo, onde a variável é uma variável livre ou de célula.

  • gh-129107: Corrige mais duas funções bytearray para threads livres.

  • gh-127705: Usa referências marcadas (_PyStackRef) para a construção padrão, bem como para a construção com threads livres. Isso tem um pequeno impacto negativo no desempenho a curto prazo, mas permitirá acelerações maiores no futuro e reduzirá significativamente os custos de manutenção, permitindo uma única implementação de referências marcadas no futuro.

  • gh-130094: Corrige duas condições de corrida envolvendo importações simultâneas que poderiam levar a falhas espúrias com ModuleNotFoundError.

  • gh-129107: Torna o iterador bytearray seguro sob threads livres.

  • gh-115802: Use o modelo de código “médio” mais eficiente para código compilado JIT em plataformas suportadas.

  • gh-107956: Um arquivo build-details.json agora está instalado no diretório da biblioteca padrão independente de plataforma (implementação da PEP 739).

  • gh-116042: Corrige local para SyntaxErrors de escapes inválidos no tokenizador. Patch por Pablo Galindo

  • gh-91079: Altera a proteção contra estouro de pilha em C para considerar a quantidade de pilha consumida, em vez de um contador. Isso permite recursão mais profunda em muitos casos, mas permanece seguro.

  • gh-129715: Melhora o tratamento do JIT experimental de retornos para chamadores desconhecidos.

Biblioteca

  • gh-129983: Corrige corrida de dados em compile_template em sre.c.

Núcleo e embutidos

  • gh-129967: Corrige uma condição de corrida na construção com threads livres quando repr(set) é chamado simultaneamente com set.clear().

  • gh-129953: A pilha interna (de avaliação) agora é transferida para a memória sempre que a execução escapa do interpretador ou do código compilado por JIT. Isso não deve ter efeito observável em Python ou em extensões embutidas, mas permitirá várias otimizações importantes no futuro.

  • gh-129515: Esclarece mensagens de erro de sintaxe para expressões condicionais quando uma instrução é especificada antes de uma palavra reservada if ou depois de uma palavra reservada else.

  • gh-129349: bytes.fromhex() e bytearray.fromhex() agora aceita ASCII bytes e objetos bytes ou similares.

  • gh-129149: Adiciona um atalho para inteiros de tamanho médio em PyLong_FromSsize_t(). Patch por Chris Eibl.

  • gh-129107: Torne o bytearray seguro em threads livres.

  • gh-128974: Corrige uma falha em UnicodeError.__str__ quando atributos personalizados implementam __str__() com efeitos colaterais. Patch por Bénédikt Tran.

  • gh-126085: typing.TypeAliasType agora oferece suporte a desempacotamento em estrela.

  • gh-125331: from __future__ import barry_as_FLUFL agora funciona em mais contextos, incluindo quando é usado em arquivos, com o sinalizador -c e no REPL quando há várias instruções na mesma linha. Anteriormente, funcionava apenas em linhas subsequentes no REPL e quando os sinalizadores apropriados eram passados diretamente para compile(). Patch por Pablo Galindo.

  • gh-121464: Torna iterações simultâneas sobre o mesmo iterador enumerate() seguras em threads livres. Consulte Estratégia para Iteradores em Threads Livres.

  • gh-87790: Suporte para sublinhado e vírgula como separadores de milhares na parte fracionária para tipos de apresentação de ponto flutuante do novo estilo de formatação de string (com format() ou Literais de strings formatadas). Patch por Sergey B Kirpichev.

  • gh-124445: Corrige a especialização de apelidos genéricos que são genéricos em uma typing.ParamSpec e foram especializados com um tipo variável aninhado.

  • gh-120608: Adapta reversed() para uso na construção com threads livres. reversed() ainda não é seguro para thread, no sentido de que iterações simultâneas podem ver o mesmo objeto, mas não corromperão o estado do interpretador.

Biblioteca

  • gh-100388: Corrige o método platform._sys_version() quando __DATE__ não estiver definido no momento da compilação, alterando a string de data e hora padrão do momento da construção para a época UNIX.

Núcleo e embutidos

  • bpo-44369: Melhoria nos erros de sintaxe para strings fechadas incorretamente. Patch por Pablo Galindo.

API C

Construção

  • gh-131035: Usa -flto=thin para tempos de construção mais rápidos usando clang-cl no Windows. Patch por Chris Eibl.

  • gh-130740: Certifica-se de que Python.h esteja incluído antes de stdbool.h, a menos que pyconfig.h esteja incluído antes ou em alguns contextos específicos da plataforma.

  • gh-130090: Construir com PlatformToolset=ClangCL no Windows agora oferece suporte a PGO (otimização guiada por perfil). Patch por Chris Eibl com apoio inestimável de Steve Dover.

  • gh-129819: Permite a construção do JIT com o interpretador de chamada de cauda.

  • gh-129989: Corrige um bug em que o interpretador da chamada de cauda era habilitado quando --without-tail-call-interp era fornecido ao script configure.

  • gh-129838: Não redefine _Py_NO_SANITIZE_UNDEFINED ao compilar com uma versão recente do GCC e um sanitizador indefinido habilitado.

  • gh-82909: #pragma-based linking with python3*.lib agora pode ser desabilitado com Py_NO_LINK_LIB. Patch por Jean-Christophe Fillion-Robin.

Python 3.14.0 alpha 5

Data de lançamento: 2025-02-11

macOS

  • gh-91132: Atualiza o instalador do macOS para usar o ncurses 6.5.

Ferramentas/Demos

  • gh-129248: O executor de testes do iOS agora remove o prefixo de log de cada linha de saída do conjunto de testes.

  • gh-104400: Corrige vários bugs na extração mudando para um analisador sintático de AST em pygettext.

Testes

  • gh-129386: Adiciona test.support.reset_code, que pode ser usado para redefinir várias otimizações em nível de bytecode e instrumentação local para uma função.

  • gh-128474: Desabilita os casos de teste test_embed que apresentam falhas de segmentação em binários de instrumentos BOLT. Os testes são desabilitados somente quando o BOLT está habilitado.

  • gh-128003: Adiciona a opção --parallel-threads=N ao executor de testes de regressão, que executa testes individuais em múltiplas threads em paralelo para encontrar bugs de simultaneidade. Observe que a maior parte do conjunto de testes ainda não foi revisada quanto à segurança de threads nem anotada com @thread_unsafe quando necessário.

Segurança

  • gh-105704: Ao usar urllib.parse.urlsplit() e urllib.parse.urlparse(), a análise de host não rejeitaria nomes de domínio contendo colchetes ([ e ]). Os colchetes são válidos somente para hosts IPv6 e IPvFuture de acordo com RFC 3986 Seção 3.2.2.

  • gh-126108: Corrige uma possível desreferência de ponteiro NULL em PySys_AddWarnOptionUnicode().

  • gh-80222: Corrige bug na dobragem (folding) de strings entre aspas ao achatar uma mensagem de e-mail usando uma política de e-mail moderna. Anteriormente, quando uma string entre aspas era dobrada para abranger mais de uma linha, as aspas circundantes e escapes internos eram omitidos. Isso poderia, teoricamente, ser usado para fazer spoof das linhas de cabeçalho usando uma string entre aspas cuidadosamente construída se o e-mail renderizado resultante fosse transmitido ou reanalisado.

  • gh-119511: Corrige uma potencial negação de serviço no módulo imaplib. Ao conectar-se a um servidor malicioso, isso poderia fazer com que uma quantidade arbitrária de memória fosse alocada. Em muitos sistemas, isso é inofensivo, pois a memória virtual não utilizada é apenas um mapeamento, mas se isso atingir um limite de tamanho de endereço virtual, pode levar a um MemoryError ou outra falha de processo. Em sistemas ou construções incomuns, onde toda a memória alocada é tocada e apoiada por RAM ou armazenamento real, isso pode ter consumido recursos ao fazer isso até travar de forma semelhante.

Biblioteca

  • gh-129939: Páginas de comparação com alterações destacadas geradas pela classe difflib.HtmlDiff agora oferecem suporte ao modo escuro.

  • gh-129928: Levanta sqlite3.ProgrammingError se uma função SQL definida pelo usuário com um número inválido de parâmetros for criada. Patch por Erlend Aasland.

  • gh-129583: Atualiza pip empacotado para 25.0.1

  • gh-129766: Corrige falha em warnings, ao chamar _release_lock() sem trava existente.

  • gh-129005: _pyio.FileIO.readall() agora aloca, redimensiona e preenche um buffer de dados usando o mesmo algoritmo que _io.FileIO.readall() usa.

  • gh-129646: Atualiza o mapeamento de apelido de localidade no módulo locale para corresponder ao mapeamento de apelido de localidade mais recente do X Org e oferecer suporte a novas localidades no Glibc 2.41.

  • gh-128317: Coloca o destaque do calendário CLI na classe privada, removendo highlight_day da API pública calendar.TextCalendar. Patch por Hugo van Kemenade.

  • gh-129603: Corrige bugs onde objetos sqlite3.Row poderiam sofrer segfault se seu description herdado fosse definido como None. Patch por Erlend Aasland.

  • gh-129559: Adiciona o método bytearray.resize() para que bytearray possa ser redimensionado eficientemente internamente.

  • gh-129502: Erros improváveis na preparação de argumentos para o retorno de chamada ctypes agora são tratados da mesma forma que erros levantados no retorno de chamada ou na conversão do resultado do retorno de chamada — usando sys.unraisablehook() em vez de sys.excepthook() e não definindo sys.last_exc e outras variáveis.

  • gh-129403: Corrigida a mensagem de ValueError para asyncio.Barrier e threading.Barrier.

  • gh-129409: Corrige um estouro de inteiro no módulo csv ao gravar um campo de dados maior que 2 GB.

  • gh-126400: Adicione um argumento nomeado de soquete timeout a logging.handlers.SysLogHandler.

  • gh-118761: Sempre faz importação preguiçosa de warnings em threading. Patch por Taneli Hukkinen.

  • gh-118761: Melhora o tempo de importação de subprocess importando locale e signal de forma preguiçosa. Patch por Taneli Hukkinen.

  • gh-129346: Em sqlite3, manipula a falta de memória ao criar funções SQL definidas pelo usuário.

  • gh-129005: Otimiza _pyio.FileIO.readinto evitando objetos e cópias desnecessários usando os.readinto().

  • gh-129195: Suporte para geração de relatórios de informações do grafo de chamadas de asyncio.staggered.staggered_race().

  • gh-129205: Adiciona os.readinto() para ler um objeto buffer de um descritor de arquivo.

  • gh-128772: Corrige pydoc para métodos com o atributo __module__ igual a None.

  • gh-129061: Corrige FORCE_COLOR e NO_COLOR quando strings vazias. Patch por Hugo van Kemenade.

  • gh-92897: Foi agendada a descontinuação do argumento check_home de sysconfig.is_python_build() para o Python 3.15.

  • gh-129064: Descontinua sysconfig.expand_makefile_vars(), em favor do uso de sysconfig.get_paths() com o argumento vars.

  • gh-128550: Foi removida uma otimização incorreta relacionada a tarefas ansiosas em asyncio.TaskGroup que resultava em cancelamentos perdidos.

  • gh-128991: Libera a referência do quadro de entrada dentro do retorno de chamada bdb

  • gh-118761: Reduz o tempo de importação de pstats e zipfile em até 20%, removendo importações desnecessárias para typing. Patch por Bénédikt Tran.

  • gh-128978: Corrige uma exceção NameError em sysconfig.expand_makefile_vars(). Patch por Bénédikt Tran.

  • gh-128961: Corrige uma falha ao definir o estado em um iterador array.array esgotado.

  • gh-128894: Corrige traceback.TracebackException._format_syntax_error para não falhar em exceções com metadados personalizados.

  • gh-128916: Não tenta definir SO_REUSEPORT em soquetes de famílias de endereços diferentes de AF_INET e AF_INET6, pois isso não faz sentido com essas famílias de endereços, e a chamada falhará com o kernel Linux 6.12.9 e mais recentes.

  • gh-118761: Melhorado o tempo de importação de tomllib removendo as importações typing, string e tomllib._types. Patch por Taneli Hukkinen.

  • gh-128679: tracemalloc: Corrige condições de corrida quando tracemalloc.stop() é chamado por uma thread, enquanto outras threads estão rastreando alocações de memória. Patch por Victor Stinner.

  • gh-128891: Adiciona opcodes especializados a opcode.opname.

  • gh-118761: Reduz o tempo de importação de gettext em até dez vezes, importando re sob demanda. Em particular, re não é mais exposto implicitamente como gettext.re. Patch por Eli Schwartz.

  • gh-118761: Reduz o tempo de importação de optparse quando nenhum texto de ajuda for impresso. Patch por Eli Schwartz.

  • gh-128657: Corrige possível referência extra ao usar objetos retornados por hashlib.sha256() em threads livres.

  • gh-118761: Reduz o tempo de importação de csv em até cinco vezes, importando re sob demanda. Em particular, re não é mais exposto implicitamente como csv.re. Patch por Bénédikt Tran.

  • gh-128308: Adiciona suporte ao argumento nomeado name para tarefas ansiosas em asyncio.loop.create_task(), asyncio.create_task() e asyncio.TaskGroup.create_task(), passando todos os kwargs para a fábrica de tarefas definida por asyncio.loop.set_task_factory().

  • gh-118761: Melhora o desempenho de base64.b16decode() em até dez vezes, verificando com mais eficiência a sequência de bytes em busca de dígitos hexadecimais. Reduz o tempo de importação de base64 em até seis vezes, não importando mais re. Patch por Bénédikt Tran, Chris Markiewicz e Adam Turner.

  • gh-128156: Ao usar o sistema macOS libffi, o suporte para tipos complexos em ctypes agora é verificado em tempo de execução (macOS 10.15 ou mais recente). Os tipos também devem estar disponíveis em tempo de construção.

  • gh-128636: Corrige falha do PyREPL quando os.environ é substituído por um valor inválido.

  • gh-128498: Padrão para stdout isatty para detecção de cor em vez de stderr. Patch por Hugo van Kemenade.

  • gh-128384: Adiciona trava para warnings para evitar algumas disputas de dados quando uma construção com threads livres for usado. Altera _warnings_runtime_state.mutex para um mutex recursivo e expõe-o a warnings, por meio das funções _acquire_lock() e _release_lock(). A trava é mantido quando filters e _filters_version são atualizados.

  • gh-128509: Adiciona sys._is_immortal() para identificar objetos imortais em tempo de execução.

  • gh-128479: Corrige asyncio.staggered.staggered_race() vazando tarefas e emitindo uma exceção não tratada.

  • gh-128427: uuid.NIL e uuid.MAX agora estão disponíveis para representar os formatos UUID Nil e Max, conforme definido por RFC 9562.

  • gh-91279: zipfile.ZipFile.writestr() agora respeita SOURCE_DATE_EPOCH que as distribuições podem definir centralmente e fazer com que as ferramentas de construção consumam isso para produzir uma saída reproduzível.

  • gh-112064: Corrige tratamento incorreto de tamanhos de leitura negativos em HTTPResponse.read. Patch por Yury Manushkin.

  • gh-58956: Corrigido um vazamento de referência de quadro em bdb.

  • gh-128131: Suporte completo ao acesso aleatório de arquivos zip somente leitura, não criptografados e descompactados obtidos por ZipFile.open.

  • gh-127975: Evita reutilizar tipos de aspas em ast.unparse() se não for necessário.

  • gh-115514: Corrige exceções e escritas incompletas após asyncio._SelectorTransport ser fechado antes das gravações serem concluídas.

  • gh-121604: Adiciona avisos de Deprecation em falta para importlib.machinery.DEBUG_BYTECODE_SUFFIXES, importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES, importlib.machinery.WindowsRegistryFinder, importlib.abc.ResourceLoader, importlib.abc.SourceLoader.path_mtime().

  • gh-127873: Quando -E estiver definido, ignora apenas PYTHON_COLORS e não FORCE_COLOR/NO_COLOR/TERM ao colorir a saída. Patch por Hugo van Kemenade.

  • gh-125413: Adiciona o atributo pathlib.Path.info, que armazena um objeto que implementa o protocolo pathlib.types.PathInfo (também novo). O objeto oferece suporte à consulta do tipo de arquivo e o armazenamento em cache interno dos resultados de stat(). Objetos de caminho gerados por iterdir() são inicializados com informações do tipo de arquivo obtidas a partir da varredura do diretório pai.

  • gh-127712: Corrige o tratamento do argumento secure de logging.handlers.SMTPHandler.

  • gh-127096: Não recria a seção sem nome em cada leitura em configparser.ConfigParser. Patch por Andrey Efremov.

  • gh-124369: Descontinua pdb.Pdb.curframe_locals

  • gh-126332: Corrige falha do _pyrepl ao dar dois CTRL-Z em uma linha que transborda.

  • gh-125553: Corrige invariância de ida e volta para continuações de contrabarra em tokenize.untokenize().

  • gh-91048: Adiciona funções asyncio.capture_call_graph() e asyncio.print_call_graph().

  • gh-124703: Sair do pdb no modo inline emitirá um prompt de confirmação e sairá normalmente, em vez de exibir um traceback de exceção.

  • gh-123987: Corrigido problema no NamespaceReader em que um item não-caminho em um caminho de espaço de nomes, como um sinalizador adicionado por um instalador editável, interrompia o carregamento de recursos.

  • gh-119349: Adiciona a função ctypes.util.dllist() para listar as bibliotecas compartilhadas carregadas para o processo atual.

  • gh-55454: Adiciona suporte a IMAP4 IDLE ao módulo imaplib. Patch por Forest.

  • gh-119257: Exibe o menu de autopreenchimento com tecla tab abaixo da linha atual, o que resulta em um comportamento menos instável e corrige um bug de movimento do cursor. Patch por Daniel Hollas

  • gh-101410: Suporte a mensagens personalizadas para erros de domínio no módulo math (math.sqrt(), math.log() e math.atanh() foram modificados como exemplos). Patch por Charlie Zhao e Sergey B Kirpichev.

  • gh-81340: Usa os.copy_file_range() nas funções shutil.copy(), shutil.copy2() e shutil.copyfile() por padrão. Uma chamada de sistema Linux subjacente oferece aos sistemas de arquivos a oportunidade de implementar o uso de cópia na gravação (no caso de btrfs e XFS) ou cópia do lado do servidor (no caso de NFS). Patch por Illia Volochii.

  • bpo-27307: Adiciona suporte a atributos e acesso a itens para string.Formatter no modo de numeração automática, o que permite strings de formato como ‘{.name}’ e ‘{[1]}’.

IDLE

  • gh-129873: Simplifica a exibição da documentação do IDLE copiando apenas a seção de texto de idle.html para idlelib/help.html. Patch por Stan Ulbrych.

Documentação

Núcleo e embutidos

  • gh-100239: Substitui o opcode BINARY_SUBSCR e sua família por BINARY_OP com oparg NB_SUBSCR.

  • gh-129732: Corrigida uma corrida em _Py_qsbr_reserve na construção com threads livres.

  • gh-129763: Remove a macro interna LLTRACE (use Py_DEBUG em vez disso).

  • gh-129715: Melhora o desempenho JIT dos geradores.

  • gh-129643: Corrige a segurança de thread de PyList_Insert() em construções com threads livres.

  • gh-129668: Corrige condição de corrida ao levantar MemoryError na construção com threads livres.

  • gh-129643: Corrige a segurança de thread de PyList_SetItem() em construções com threads livres. Patch por Kumar Aditya.

  • gh-128563: Corrige um problema em que o recurso de depuração “lltrace” poderia ter sido habilitado incorretamente para alguns quadros.

  • gh-129393: No FreeBSD, sys.platform não contém mais a versão principal. É sempre 'freebsd', em vez de 'freebsd13' ou 'freebsd14'.

Biblioteca

  • gh-129345: Corrige desreferência de ponteiro nulo em syslog.openlog() quando um gancho de auditoria levanta uma exceção.

Núcleo e embutidos

  • gh-129231: Melhora o layout de memória dos rastreamentos JIT. Patch por Diego Russo

  • gh-129149: Adiciona um caminho rápido para inteiros de tamanho médio em PyLong_FromUnsignedLong(), PyLong_FromUnsignedLongLong() e PyLong_FromSize_t().

  • gh-129201: A versão com threads livres do coletor de lixo cíclico foi otimizada para usar condicionalmente instruções de pré-busca da CPU durante a coleta. Isso pode reduzir o tempo de coleta, aumentando a probabilidade de os dados estarem no cache da CPU quando necessário. As instruções de pré-busca são habilitadas se o número de objetos de longa duração (objetos que sobrevivem a uma coleta completa) exceder um limite.

  • gh-129093: Corrige f-strings como f'{expr=}' que às vezes não exibem a expressão completa quando a expressão contém !=.

  • gh-124363: Trata expressões de depuração em f-string como strings brutas. Patch por Pablo Galindo

  • gh-128714: Corrige as possíveis corridas nos métodos especiais get/set __annotations__, __annotate__ e __type_params__ para o objeto função e adiciona testes relacionados.

  • gh-128799: Adiciona o quadro except* ao traceback quando ele encapsula uma exceção simples.

  • gh-128842: Coleta estatísticas de memória JIT usando pystats. Patch por Diego Russo.

  • gh-100239: Especializa BINARY_OP para operações lógicas bit a bit em inteiros compactos.

  • gh-128910: As funções privadas, não documentadas e não utilizadas _PyTrash_begin e _PyTrash_end da API C foram removidas.

  • gh-128807: Adiciona uma fase de marcação ao coletor de lixo com threads livres. Isso é semelhante ao que foi feito em gh-126491. Como o coletor de lixo com threads livres não possui gerações e não é incremental, a fase de marcação procura todos os objetos acessíveis a partir de raízes conhecidas. As raízes são objetos que se sabe não serem lixo, como o dicionário de módulos para sys. Para a maioria dos programas, essa fase de marcação deve tornar o coletor de lixo um pouco mais rápido, já que normalmente menos trabalho é feito por objeto.

  • gh-100239: Adiciona o opcode BINARY_OP_EXTEND que executa um par de funções (funções de guarda e especialização) acessadas do cache inline.

  • gh-128563: Um novo tipo de interpretador foi adicionado ao CPython. Este interpretador utiliza chamadas de cauda para seus manipuladores de instruções. Resultados preliminares de benchmark sugerem uma velocidade média geométrica de 7 a 11% no pyperformance (dependendo da plataforma) e até 30% mais rápida em cargas de trabalho com uso intensivo de Python. Atualmente, este interpretador funciona apenas em compiladores mais recentes, como o clang-19. Outros compiladores continuarão usando o interpretador antigo. Patch por Ken Jin, com ideias de como implementar isso no CPython por Mark Shannon, Garret Gu, Haoran Xu e Josh Haberman.

  • gh-126703: Melhora o desempenho da iteração em listas e tuplas usando uma lista livre para os objetos iterador.

  • gh-127953: O tempo para manipular um evento LINE em sys.monitoring (e sys.settrace) agora é independente do número de linhas no objeto de código.

  • gh-128330: Restaura caracteres de controle do terminal na saída do REPL.

  • gh-128016: A mensagem SyntaxWarning para sequências de escape inválidas foi aprimorada para esclarecer que tais sequências levantarão um SyntaxError em versões futuras do Python. A nova mensagem também sugere uma possível correção, ou seja, Did you mean "\\e"?.

  • gh-126004: Corrige o tratamento dos valores UnicodeError.start e UnicodeError.end no tratador de erros codecs.replace_errors(). Patch por Bénédikt Tran.

  • gh-126004: Corrige o tratamento dos valores UnicodeError.start e UnicodeError.end no tratador de erros codecs.backslashreplace_errors(). Patch por Bénédikt Tran.

  • gh-126004: Corrige o tratamento dos valores UnicodeError.start e UnicodeError.end no tratador de erros codecs.xmlcharrefreplace_errors(). Patch por Bénédikt Tran.

  • gh-127119: Otimiza ligeiramente o desalocador int.

  • gh-127349: Corrigido o erro ao redimensionar o terminal no Python REPL. Patch por Semyon Moroz.

  • gh-125723: Corrige falha com gi_frame.f_locals quando os frames do gerador duram mais que o gerador. Patch por Mikhail Efimov.

Biblioteca

Núcleo e embutidos

  • gh-115911: Se o diretório de trabalho atual não puder ser determinado devido às permissões, a importação não levantará mais PermissionError. Patch por Alex Willmer.

Biblioteca

API C

Construção

  • gh-129660: Remove test_embed do treinamento de PGO, cuja contribuição em versões recentes é considerada ignorável.

  • gh-128902: Corrige erros de compilação com Clang 9 e versões anteriores devido à falta de suporte a __attribute__((fallthrough)).

Python 3.14.0 alpha 4

Data de lançamento: 2025-01-14

macOS

  • gh-127592: O uso das APIs unificadas do Apple System Log foi desabilitado quando a versão mínima do macOS era anterior à 10.12.

Ferramentas/Demos

  • gh-128152: Corrige um bug em que o analisador de pré-processador C da Argument Clinic tentava analisar diretivas de pré-processador dentro de comentários C. Patch por Erlend Aasland.

Testes

  • gh-128690: Temporariamente, não use test_embed em construções de perfil PGO até que o problema com test_init_pyvenv_cfg falhando em algumas configurações seja resolvido.

Biblioteca

  • gh-128731: Corrige ResourceWarning em urllib.robotparser.RobotFileParser.read().

  • gh-71339: Adiciona novos métodos de asserção para unittest: assertHasAttr(), assertNotHasAttr(), assertIsSubclass(), assertNotIsSubclass() assertStartsWith(), assertNotStartsWith(), assertEndsWith() e assertNotEndsWith().

  • gh-118761: Melhora o tempo de importação de pickle em 25% removendo uma expressão regular desnecessária. Dessa forma, re não está mais implicitamente disponível como pickle.re. Patch por Bénédikt Tran.

  • gh-128661: Corrige typing.evaluate_forward_ref() não mostrando descontinuação quando o argumento type_params não é passado.

  • gh-128562: Corrige possíveis conflitos nos nomes dos widgets tkinter gerados se o nome da classe do widget terminar com um dígito.

  • gh-128559: Tempo de importação melhorado de asyncio.

  • gh-128552: Corrige lixo cíclico introduzido por asyncio.loop.create_task() e asyncio.TaskGroup.create_task() mantendo uma referência à tarefa criada se ela estiver ansiosa.

  • gh-128340: Adiciona um identificador interno seguro para thread para ser usado em asyncio.loop.call_soon_threadsafe() para cancelamento seguro para thread.

  • gh-128182: Corrige falha ao usar ponteiros ctypes simultaneamente na construção com threads livres.

  • gh-128400: Exibe somente a thread atual em faulthandler na construção com threads livres para evitar corridas.

  • gh-128400: Corrige falha ao usar faulthandler.dump_traceback() enquanto outras threads estiverem ativas na construção com threads livres.

  • gh-128388: Corrige PyREPL no Windows para oferecer suporte a mais atalhos de teclado, como os atalhos de teclado para pular palavras Control-← e Control-→ e aqueles com meta (isto é, Alt), por exemplo, Alt-d para kill-word ou Alt-Backspace para backward-kill-word.

  • gh-88834: Unifica a verificação de instância para typing.Union e types.UnionType: Union agora usa as verificações de instância em relação aos seus parâmetros em vez das verificações de subclasse.

  • gh-128302: Corrige xml.dom.xmlbuilder.DOMEntityResolver.resolveEntity(), que foi quebrado pela transição do Python 3.0.

  • gh-128317: Realça today em cores na saída da CLI do calendar. Patch por Hugo van Kemenade.

  • gh-128302: Permite que xml.dom.xmlbuilder.DOMParser.parse() manipule corretamente instâncias xml.dom.xmlbuilder.DOMInputSource que tenham apenas um atributo systemId definido.

  • gh-128151: Melhoria de 30% na geração de objetos UUID nas versões 3, 4, 5 e 8 por meio de suas funções dedicadas. Patch por Bénédikt Tran.

  • gh-128118: Melhora o desempenho de copy.copy() em 30% por meio de um caminho rápido para tipos atômicos e tipos de contêiner.

  • gh-127946: Corrige falha ao modificar objetos ctypes._CFuncPtr simultaneamente na construção com threads livres.

  • gh-128062: Reverte a fonte da barra de menu do turtledemo para seu valor padrão e exibe as teclas de atalho na posição correta.

  • gh-128014: Corrige a redefinição do ícone da janela padrão passando default='' para o método wm_iconbitmap() do tkinter.

  • gh-41872: Corrige extração rápida de docstrings de módulo de um arquivo em pydoc. Agora ele oferece suporte a docstrings com aspas simples, sequências de escape, literais de strings brutas e outras sintaxes Python.

  • gh-127060: Define a variável de ambiente TERM como “dumb” para desabilitar cores de traceback no IDLE, já que o IDLE não entende sequências de escape ANSI. Patch por Victor Stinner.

  • gh-126742: Corrige o suporte de mensagens de erro localizadas relatadas por dlerror(3) e gdbm_strerror nas funções ctypes e dbm.gnu respectivamente. Patch por Bénédikt Tran.

  • gh-122548: Adiciona dois novos eventos locais ao sys.monitoring, BRANCH_LEFT e BRANCH_RIGHT. Isso permite que os dois braços de ramificação sejam desabilitados independentemente, o que deve melhorar significativamente o desempenho das ferramentas de cobertura em nível de ramificação. O antigo evento de ramificação, BRANCH, agora está descontinuado.

  • gh-127847: Corrige a posição ao fazer buscas e leituras intercaladas em arquivos zip não compactados e não criptografados retornados por zipfile.ZipFile.open().

  • gh-127688: Adiciona as constantes SCHED_DEADLINE e SCHED_NORMAL ao módulo os.

  • gh-83662: Adiciona o método __class_getitem__ ausente à implementação Python de functools.partial(), para torná-lo compatível com a versão C. Isso é relevante principalmente para implementações Python alternativas como PyPy e GraalPy, porque o CPython geralmente usará a implementação C dessa função.

  • gh-127586: multiprocessing.pool.Pool agora restaura corretamente os manipuladores de sinais bloqueados da thread mãe ao criar processos via spawn ou forkserver.

  • gh-98188: Corrige um problema em email.message.Message.get_payload() onde os dados não podem ser decodificados se o mecanismo de Codificação de Transferência de Conteúdo contiver espaços em branco à direita ou texto lixo adicional. Patch por Hui Liu.

  • gh-127529: Corrige o comportamento de asyncio.selector_events.BaseSelectorEventLoop._accept_connection() ao lidar com ConnectionAbortedError em um laço. Isso melhora o desempenho no OpenBSD.

  • gh-127360: Quando uma mensagem de erro descritiva não pode ser fornecida para um ssl.SSLError, a mensagem “erro desconhecido” agora mostra o código de erro interno (conforme recuperado por ERR_get_error e funções OpenSSL semelhantes).

  • gh-127196: Corrige falha quando um dicionário com chaves em codificação inválida era passado para diversas funções no módulo _interpreters.

  • gh-124130: Corrige um bug na correspondência da expressão regular \B em uma string de entrada vazia. Agora é sempre o oposto de \b. Para obter um comportamento antigo, use (?!\A\Z)\B. Para obter um novo comportamento em versões antigas do Python, use (?!\b).

  • gh-126639: tempfile.NamedTemporaryFile agora emitirá um ResourceWarning quando for finalizado pelo coletor de lixo sem ser explicitamente fechado.

  • gh-126624: Expõe o código de erro XML_ERROR_NOT_STARTED do Expat >=2.6.4 em xml.parsers.expat.errors.

  • gh-126225: getopt e optparse não estão mais marcados como descontinuados. Há razões legítimas para usar um desses módulos em preferência a argparse, e nenhum desses módulos corre o risco de ser removido da biblioteca padrão. Dos três, argparse continua sendo a escolha padrão recomendada, a menos que uma das preocupações observadas no topo da documentação do módulo optparse se aplique.

  • gh-124761: Adiciona a constante SO_REUSEPORT_LB ao socket para FreeBSD.

  • gh-121720: enum.EnumDict agora pode ser usada sem recorrer à API privada.

  • gh-123424: Adicionada zipfile.ZipInfo._for_archive() definindo propriedades padrão em objetos ZipInfo. Patch por Bénédikt Tran e Jason R. Coombs.

  • gh-121676: Descontinua a chamada da implementação Python de functools.reduce() com uma function ou sequence como um argumento nomeado. Isso será proibido no Python 3.16 para corresponder à implementação em C.

  • gh-112015: ctypes.memoryview_at() agora existe para criar um objeto memoryview que se refere ao ponteiro e comprimento fornecidos. Isso funciona como ctypes.string_at(), exceto que evita uma cópia de buffer e é normalmente útil ao implementar funções de retorno de chamada Python puras que recebem buffers de tamanho dinâmico.

  • gh-95371: Adicionado suporte para outros formatos de imagem (PNG, PGM e PPM) ao módulo turtle. Patch por Shin-myoung-serp.

Núcleo e embutidos

  • gh-128078: Corrige um SystemError ao usar anext() com um valor de tupla padrão. Patch por Bénédikt Tran.

  • gh-128717: Corrige uma falha ao definir o limite de recursão enquanto outros threads estão ativos na construção com threads livres.

  • gh-124483: Trata Py_DECREF e variantes como escape ao gerar opcode e metadados UOP. Isso evita a possibilidade de um método __del__ causar comportamento incorreto do JIT.

  • gh-126703: Melhora o desempenho dos métodos de classe usando uma freelist.

  • gh-128137: Atualização do layout PyASCIIObject para manipular campos internos com a operação atômica. Patch por Donghee Na.

Biblioteca

  • gh-128192: Atualiza o algoritmo de autenticação de resumo HTTP para urllib.request dando suporte à autenticação de resumo SHA-256 conforme especificado em RFC 7616.

Núcleo e embutidos

  • gh-126868: Aumenta o uso de freelist para alocação de int.

  • gh-114203: Otimiza Py_BEGIN_CRITICAL_SECTION para chamadas recursivas simples.

  • gh-127705: Adiciona depuração de stackref quando Py_STACKREF_DEBUG está definido. Encontra todos os fechamentos duplos e vazamentos, registrando a origem e o último empréstimo.

    Inspirado no modo de depuração do HPy. https://docs.hpyproject.org/en/latest/debug-mode.html

  • gh-128079: Corrige um bug em que except* não verifica corretamente o valor de retorno de uma função split() de ExceptionGroup, levando a uma falha em alguns casos. Agora, quando split() retorna um objeto inválido, except* levanta TypeError com o objeto ExceptionGroup levantado originalmente encadeado a ele.

  • gh-128030: Evita erro ao chamar PyModule_GetFilenameObject em um objeto que não é módulo ao importar um símbolo inexistente de um objeto que não é módulo.

Biblioteca

  • gh-128035: Indica através de ssl.HAS_PHA se o módulo ssl oferece suporte a autenticação de cliente pós-handshake (PHA) TLSv1.3. Patch por Will Childs-Klein.

Núcleo e embutidos

  • gh-127274: Adiciona um novo sinalizador, CO_METHOD, a co_flags que indica se o objeto código pertence a uma função definida no escopo da classe.

  • gh-66409: Durante a inicialização do caminho, agora verificamos se base_exec_prefix é o mesmo que base_prefix antes de retornar à pesquisa no diretório do interpretador Python.

  • gh-127970: Agora usamos o local da biblioteca de tempo de execução libpython usada no processo atual para determinar sys.base_prefix em todas as plataformas que implementam a função dladdr definida pelo padrão UNIX — isso inclui Linux, Android, macOS, iOS, FreeBSD, etc. Isso já acontecia nas construções do Windows e do macOS Framework.

  • gh-127773: Não usa o cache de atributos de tipo para tipos com uma MRO incompatível.

  • gh-127903: Objects/unicodeobject.c: corrige uma falha em compilações de depuração em _copy_characters quando não há nada para copiar.

  • gh-127809: Corrige um problema em que o JIT experimental pode inferir um tipo de resultado incorreto para exponenciação (** e **=), levando a bugs ou travamentos.

  • gh-126862: Corrige um possível estouro quando uma classe herda de um número absurdo de superclasses. Reportado por Valery Fedorenko. Patch por Bénédikt Tran.

API C

Construção

  • gh-128627: Para construções do Emscripten, a chamada de conversão do ponteiro de função trampoline agora usa a instrução wasm-gc ref.test se estiver disponível em vez da reflexão do tipo Wasm JS.

  • gh-128472: Ignora a otimização BOLT de funções usando gotos computados, corrigindo erros na compilação com LLVM 19.

  • gh-115765: O GNU Autoconf 2.72 agora é necessário para gerar o configure. Patch de Erlend Aasland.

  • gh-123925: Corrige a construção do módulo curses em plataformas com libncurses, mas sem libncursesw.

  • gh-90905: Adiciona suporte para compilação cruzada para x86_64 no macOS aarch64/arm64.

  • gh-128321: Define LIBS em vez de LDFLAGS ao verificar se as funções de biblioteca sqlite3 estão disponíveis. Isso corrige a ordenação de bibliotecas vinculadas durante as verificações, que era incorreta ao usar uma libsqlite3 vinculada estaticamente.

  • gh-100384: Erro em unguarded-availability em construções do macOS, impedindo o uso inválido de símbolos que não estão disponíveis em versões mais antigas do sistema operacional.

  • gh-128104: Remoção das condições Py_STRFTIME_C99_SUPPORT em favor da exigência de suporte ao especificador C99 strftime(3) em tempo de construção. Na compilação cruzada, não há verificação em tempo de construção e o suporte é presumido.

  • gh-127951: Adiciona a opção --pystats à construção do Windows para habilitar a coleta de estatísticas de desempenho.

Python 3.14.0 alpha 3

Data de lançamento: 2024-12-17

Windows

  • gh-127353: Permite forçar a saída de cores no Windows usando variáveis de ambiente. Patch por Andrey Efremov.

  • gh-125729: Torna a presença do módulo turtle dependente da opção do instalador Tcl/Tk. Anteriormente, o módulo era sempre instalado, mas seria inutilizável sem o Tcl/Tk.

Ferramentas/Demos

  • gh-126700: Adiciona suporte para funções multi-argumentos gettext em pygettext.py.

Testes

  • gh-127906: Testa a API C limitada em test_cppext. Patch por Victor Stinner.

  • gh-127637: Adiciona testes para a interface de linha de comando dis. Patch por Bénédikt Tran.

  • gh-126925: Os resultados dos testes do iOS agora são transmitidos durante a execução do teste, e o xcresulttool descontinuado não é mais usado.

  • gh-127076: Desabilita testes de chamada de sistema baseados em strace quando LD_PRELOAD estiver definido.

  • gh-127076: Filtra chamadas mmap, munmap e mprotect relacionadas à memória daquelas relacionadas ao arquivo ao testar o comportamento de io usando strace.

Segurança

Biblioteca

  • gh-126907: Corrige falha ao usar atexit simultaneamente na construção com threads livres.

  • gh-127870: Detecta chamadas recursivas no tratamento de ctypes _as_parameter_. Patch por Victor Stinner.

  • gh-127732: O módulo platform agora detecta corretamente o Windows Server 2025.

  • gh-126789: Corrigidas sysconfig.get_config_vars(), sysconfig.get_paths() e similares, que retornavam dados em cache desatualizados caso o valor de sys.prefix ou sys.exec_prefix fosse alterado. A substituição de sys.prefix ou sys.exec_prefix ainda é desencorajada, pois isso poderia danificar outras partes do código.

  • gh-127718: Adiciona cor à saída de ajuda do test.regrtest. Patch por Hugo van Kemenade.

  • gh-127610: Adicionada validação para mais de um parâmetro var-posicional ou var-keyword em inspect.Signature. Patch por Maxim Ageev.

  • gh-127627: Adicionado posix._emscripten_debugger() para ajudar na depuração do conjunto de testes no alvo Emscripten.

  • gh-126821: As aplicações de macOS e iOS agora podem escolher redirecionar stdout e stderr para o log do sistema durante a configuração do interpretador.

  • gh-93312: Inclui <sys/pidfd.h> para obter a constante os.PIDFD_NONBLOCK. Patch por Victor Stinner.

  • gh-127481: Adiciona a constante EPOLLWAKEUP ao módulo select.

  • gh-127065: Torna operator.methodcaller() seguro para thread e seguro para reentrância.

  • gh-127321: pdb.set_trace() não parará em um opcode que não tenha mais um número de linha associado.

  • gh-127429: Corrigido um bug em que, em construções cruzadas, os dados POSIX sysconfig estavam sendo gerados com o Makefile do Python host. Os dados agora são gerados a partir do Makefile da construção atual.

  • gh-127413: Adiciona a opção de linha de comando dis --specialized para mostrar o bytecode especializado. Patch por Bénédikt Tran.

  • gh-125413: Reverte a adição de pathlib.Path.scandir(). Este método foi adicionado na versão 3.14.0a2. As otimizações permanecem para caminhos do sistema de arquivos, mas outras subclasses devem implementar apenas pathlib.Path.iterdir().

  • gh-127257: Em ssl, falhas de chamada de sistema que o OpenSSL relata usando ERR_LIB_SYS agora são levantadas como OSError.

  • gh-59705: No Linux, threading.Thread agora define o nome da thread para o sistema operacional. Patch por Victor Stinner.

  • gh-127303: Expõe publicamente EXACT_TOKEN_TYPES em token.__all__.

  • gh-127331: ssl pode mostrar descrições de erros adicionados no OpenSSL 3.4.

  • gh-123967: Corrige o manipulador de falhas para quadros de trampolim. Se o quadro mais alto for um quadro de trampolim, pule-o. Patch por Victor Stinner.

  • gh-127178: Um arquivo _sysconfig_vars_(...).json agora está disponível no diretório da biblioteca padrão. Ele contém a saída de sysconfig.get_config_vars() no ambiente padrão, codificada como dados JSON. Este é um detalhe de implementação e pode mudar a qualquer momento.

  • gh-127072: Remove constantes socket.NETLINK_* desatualizadas que não estão presentes nos kernels Linux posteriores à versão 2.6.17.

  • gh-127255: A função CopyComPointer() agora é pública. Anteriormente, era privada e estava disponível apenas em _ctypes.

  • gh-127182: Corrige o travamento de io.StringIO.__setstate__(), quando None foi passado como o primeiro valor.

  • gh-127217: Corrige urllib.request.pathname2url() para caminhos começando com várias barras no Posix.

  • gh-125866: urllib.request.pathname2url() agora adiciona uma autoridade vazia ao gerar uma URL para um caminho que começa com exatamente uma barra. Por exemplo, o caminho /etc/hosts é convertido para a URL sem esquema ///etc/hosts. Como resultado dessa alteração, URLs sem autoridades são geradas apenas para caminhos relativos.

  • gh-127221: Adiciona cor à saída do unittest. Patch por Hugo van Kemenade.

  • gh-127035: Corrige shutil.which no Windows. Agora ele analisa a correspondência direta se e somente se o comando termina com uma extensão PATHEXT ou X_OK não está no modo. Suporta arquivos sem extensão se “.” estiver em PATHEXT. Suporta extensões PATHEXT que terminam com um ponto.

  • gh-122273: Suporte ao histórico de PyREPL no Windows. Patch por devdanzin e Victor Stinner.

  • gh-125866: urllib.request.pathname2url() e url2pathname() não convertem mais letras de unidade do Windows para maiúsculas.

  • gh-127078: Corrige o problema em que urllib.request.url2pathname() falhava ao descartar uma barra extra antes de uma unidade UNC no caminho da URL no Windows.

  • gh-126766: Corrige o problema em que urllib.request.url2pathname() falhava ao descartar qualquer autoridade ‘localhost’ presente na URL.

  • gh-127065: Corrige o travamento ao chamar uma instância operator.methodcaller() de vários threads na construção com threads livres.

  • gh-127090: Corrigimos o valor de urllib.response.addinfourl.url para URLs file: que expressam caminhos relativos e absolutos do Windows. A URL canônica gerada por urllib.request.pathname2url() agora é usada.

  • gh-126992: Corrige os opcodes LONG e INT para usar apenas a base 10 na conversão de string para inteiro em pickle.

  • gh-126997: Corrige o suporte de opcodes STRING e GLOBAL com argumentos não ASCII em pickletools. pickletools.dis() agora emite bytes não ASCII em argumentos STRING, BINSTRING e SHORT_BINSTRING como escape (\\xXX).

  • gh-126316: grp: Torna grp.getgrall() seguro para thread adicionando um mutex. Patch por Victor Stinner.

  • gh-126618: Corrige a representação de objetos itertools.count quando o valor da contagem é sys.maxsize.

  • gh-126615: A exceção COMError agora é pública. Anteriormente, ela era privada e estava disponível apenas em _ctypes.

  • gh-126985: Ao executar em um ambiente virtual com o site desativado (consulte -S), sys.prefix e sys.base_prefix agora apontarão para o ambiente virtual, em vez da instalação base.

  • gh-112192: No módulo trace, aumenta a precisão da cobertura (cov%) para uma casa decimal.

  • gh-118761: Melhora o tempo de importação do mimetypes em cerca de 11 a 16 vezes. Patch por Hugo van Kemenade.

  • gh-126947: Levanta um erro TypeError em _pydatetime.timedelta.__new__() se os argumentos passados não forem int ou float, para que a implementação em Python esteja em conformidade com a implementação em C.

  • gh-126946: Melhora a mensagem de erro GetoptError quando um prefixo de opção longo corresponder a várias opções aceitas em getopt.getopt() e getopt.gnu_getopt().

  • gh-126899: Faz com que os métodos do widget tkinter after() e after_idle() aceitem argumentos passados como nomeados.

  • gh-85168: Corrige problema em que urllib.request.url2pathname() e pathname2url() sempre usavam UTF-8 ao citar e descitar URIs de arquivo. Agora eles usam tratador de erros e codificação do sistema de arquivos.

  • gh-126780: Corrige os.path.normpath() para caminhos relativos à unidade no Windows.

  • gh-126775: Torna linecache.checkcache() seguro para thread e seguro para reentrada do GC.

  • Corrige problema em que urllib.request.pathname2url() levantava OSError ao receber um caminho do Windows contendo um caractere de dois pontos que não seguia uma letra de unidade, como antes de um fluxo de dados alternativo NTFS.

  • gh-126727: locale.nl_langinfo(locale.ERA) agora retorna vários segmentos de descrição de era separados por ponto e vírgula. Anteriormente, ele retornava apenas o primeiro segmento em plataformas com Glibc.

  • gh-85046: Adiciona o código de erro EHWPOISON para errno.

  • gh-118201: Falhas intermitentes corrigidas de os.confstr, os.pathconf e os.sysconf no iOS e no Android.

  • gh-86463: O parâmetro usage de argparse.ArgumentParser não afeta mais o valor padrão do parâmetro prog em subanalisadores.

  • gh-124008: Corrige possível travamento (na construção de depuração), saída incorreta ou retorno de valor incorreto do binário bruto write() ao gravar no console no Windows.

  • gh-123401: O módulo http.cookies agora suporta análise de formatos de data obsoletos de RFC 850, de acordo com os requisitos do RFC 9110. Patch por Nano Zheng.

  • gh-122431: readline.append_history_file() agora levanta ValueError quando recebe um valor negativo.

  • gh-122356: Garante que a posição de um objeto arquivo ou similar passado para zipfile.is_zipfile() permaneça inalterada após a chamada. Patch por Bénédikt Tran.

  • gh-122288: Melhora o desempenho de fnmatch.translate() em 1,7 vezes. Patch por Bénédikt Tran.

  • gh-88110: Corrigido multiprocessing.Process relatando um .exitcode de 1 mesmo em caso de sucesso ao usar o método de início "fork" ao usar um concurrent.futures.ThreadPoolExecutor.

  • gh-97514: Foi adicionada autenticação ao socket de controle do método de inicialização do forkserver do mod multiprocessing, de forma que apenas processos com a chave de autenticação gerada pelo processo que criou o forkserver possam controlá-lo. Isso representa uma melhoria em relação às outras correções do gh-97514, de modo que o acesso não seja mais limitado apenas pelas permissões do sistema de arquivos.

    A troca de descritores de arquivo dos encadeamento de controle com o processo de trabalho bifurcado agora exige o envio explícito de um byte de confirmação pelo socket após a troca em todas as plataformas que suportam o forkserver. Isso facilita bastante o teste do procedimento descrito acima.

Documentação

Núcleo e embutidos

  • gh-127740: Corrige a mensagem de erro em bytes.fromhex() quando é dado um número ímpar de dígitos para indicar corretamente que é necessário um número par de dígitos hexadecimais.

  • gh-127058: PySequence_Tuple agora cria a tupla resultante atomicamente, evitando que tuplas parcialmente criados sejam visíveis para o coletor de lixo ou através de gc.get_referrers().

  • gh-127599: Corrige estatísticas para incrementos de contagens de referências de objetos (em particular, quando uma contagem de referências foi aumentada em mais de 1 em uma única operação).

  • gh-127651: Ao levantar ImportError para símbolos ausentes em importações from, use __file__ na mensagem de erro se __spec__.origin não for um local

  • gh-127582: Corrige ressurreição de objeto não seguro para thread ao chamar finalizadores e retornos de chamada do observador na construção com threads livres.

  • gh-127434: Os shims do compilador iOS agora podem aceitar argumentos com espaços.

  • gh-127536: Adiciona travas faltando em torno de algumas operações de atribuição de lista na construção com threads livres.

  • gh-127085: Corrigido problema de condição de corrida ao exportar um buffer de um objeto memoryview na construção com threads livres.

  • gh-127238: Corrige mensagem de erro de sys.set_int_max_str_digits().

  • gh-113841: Corrige possível comportamento indefinido de divisão por zero em complex’s _Py_c_pow().

Biblioteca

Núcleo e embutidos

  • gh-126491: Adiciona uma fase de marcação ao coletor de lixo (GC). Todos os objetos que podem ser alcançados transitivamente a partir de módulos embutidos ou da pilha são marcados como alcançáveis antes da detecção de ciclos. Isso reduz a quantidade de trabalho realizada pelo GC em aproximadamente metade.

  • gh-127020: Corrige uma falha na construção com threads livres quando PyCode_GetCode(), PyCode_GetVarnames(), PyCode_GetCellvars() ou PyCode_GetFreevars() eram chamados de várias threads ao mesmo tempo.

  • gh-127010: Simplifica o rastreamento de dicionários pelo coletor de lixo. Todos os dicionários são rastreados no momento da criação, em vez de serem rastreados de forma preguiçosa quando um objeto rastreável é adicionado a eles. Isso simplifica consideravelmente o código e resulta em um pequeno ganho de velocidade.

  • gh-126980: Corrige __buffer__() de bytearray travando quando READ ou WRITE são passados como sinalizadores.

  • gh-126937: Corrigida TypeError que ocorria quando uma ctypes.Structure tinha um tamanho de campo que não cabia em um inteiro sem sinal de 16 bits. Em vez disso, o número máximo de bits era definido como sys.maxsize.

  • gh-126868: Aumenta o desempenho de int adicionando uma lista livre para inteiros compactos.

  • gh-126881: Corrige falha na finalização do estado dtoa. Patch por Kumar Aditya.

  • gh-126892: Exige que o código frio ou inválido “aqueça” antes de ser compilado JIT novamente.

  • gh-126091: Garante que os stacks trace estejam completos ao lançar em uma cadeia de geradores que termina em um gerador personalizado.

  • gh-126024: Otimiza a decodificação de sequências curtas de UTF-8 contendo caracteres não ASCII em aproximadamente 15%.

  • gh-125420: Adiciona o memoryview.index() aos objetos memoryview. Patch por Bénédikt Tran.

  • gh-125420: Adiciona o memoryview.count() aos objetos memoryview. Patch por Bénédikt Tran.

  • gh-124470: Corrige problema de travamento em construções com threads livres ao substituir o dicionário de objetos enquanto se lê um atributo em outra thread.

  • gh-69639: Implementa regras aritméticas de modo misto, combinando números reais e números complexos, conforme especificado pelos padrões C desde o C99. Patch por Sergey B Kirpichev.

  • gh-120010: Corrige casos extremos inválidos que resultavam em saídas como (nan+nanj) na multiplicação de números complexos, por exemplo, (1e300+1j)*(nan+infj). Patch por Sergey B Kirpichev.

  • gh-109746: Se _thread.start_new_thread() falhar ao iniciar uma nova thread, ele exclui seu estado do interpretador e, portanto, evita sua limpeza repetida na finalização.

API C

Construção

  • gh-127865: Corrige falha de construção em sistemas sem suporte a thread-locals.

  • gh-127629: Emscripten builds now include ctypes support.

  • gh-127111: Updated the Emscripten web example to use ES6 modules and be built into a distinct web_example subfolder.

  • gh-115869: Make jit_stencils.h (which is produced during JIT builds) reproducible.

  • gh-126898: The Emscripten build of Python is now based on ES6 modules.

Python 3.14.0 alpha 2

Data de lançamento: 2024-11-19

Windows

  • gh-126911: Atualiza a saída do comando credits.

  • gh-118973: Garante que a instalação experimental de threads livres inclua o módulo _tkinter. O componente Tcl/Tk opcional também deve ser instalado para que o módulo funcione.

  • gh-126497: Corrige a falha do venv devido à ausência de executáveis do redirecionador em instalações experimentais de threads livres.

  • gh-126074: Remoção de DLLs desnecessárias do pacote incorporável do Windows

  • gh-125315: Evita travamentos em platform devido a chamadas WMI lentas em algumas máquinas Windows.

  • gh-126084: Corrige o venvwlauncher para iniciar o pythonw em vez do python para que nenhuma janela de console extra seja criada.

  • gh-125842: Corrige uma SystemError quando sys.exit() é chamado com 0xffffffff no Windows.

  • gh-125550: Habilita o Gerenciador de instalação do Python para detectar instalações do Python 3.14 da Windows Store.

  • gh-123803: All Windows code pages are now supported as “cpXXX” codecs on Windows.

Ferramentas/Demos

  • gh-126807: Corrige avisos de extração em pygettext.py causados por definições de função equivocadas para chamadas de função.

  • gh-126167: O conjunto de textos do iOS foi modificado para que possa ser usado por projetos de terceiros para fins de teste.

Testes

  • gh-126909: Corrige testes de atributo estendido test_os para funcionar em sistemas de arquivos com limite de tamanho xattr de 1 KiB.

  • gh-125730: Change make test to not run GUI tests by default. Use make ci to run tests with GUI tests instead.

  • gh-124295: Adiciona testes de tradução ao módulo argparse.

Segurança

Biblioteca

  • gh-85957: Add missing MIME types for images with RFCs: emf, fits, g3fax, jp2, jpm, jpx, t38, tiff-fx and wmf. Patch by Hugo van Kemenade.

  • gh-126920: Fix the prefix and exec_prefix keys from sysconfig.get_config_vars() incorrectly having the same value as sys.base_prefix and sys.base_exec_prefix, respectively, inside virtual environments. They now accurately reflect sys.prefix and sys.exec_prefix.

  • gh-67877: Corrige vazamentos de memória quando a correspondência de expressão regular termina abruptamente, seja por causa de um sinal ou porque a alocação de memória falha.

  • gh-125063: marshal now supports slice objects. The marshal format version was increased to 5.

  • gh-126789: Corrigidos os valores de sysconfig.get_config_vars(), sysconfig.get_paths() e seus irmãos quando a inicialização de site acontece após sysconfig ter construído um cache para sysconfig.get_config_vars().

  • gh-126188: Atualiza pip empacotado para 24.3.1

  • gh-126766: Corrige problema em que urllib.request.url2pathname() falhava ao descartar duas barras iniciais introduzindo uma seção de autoridade vazia.

  • gh-126705: Allow os.PathLike to be a base for Protocols.

  • gh-126699: Permite que collections.abc.AsyncIterator seja uma base para Protocols.

  • gh-126654: Corrige falha quando um objeto não dicionário era passado para várias funções no módulo _interpreters.

  • gh-104745: Limita o início de um patcher (de unittest.mock.patch() ou unittest.mock.patch.object()) mais de uma vez sem pará-lo

  • gh-126595: Corrige falha ao instanciar itertools.count com uma contagem inicial de sys.maxsize em construções de depuração. Patch por Bénédikt Tran.

  • gh-120423: Corrige problema em que urllib.request.pathname2url() manipulava incorretamente caminhos do Windows com barras inseridas.

  • gh-126565: Melhora o desempenho de zipfile.Path.open() para modos que não sejam de leitura.

  • gh-126505: Corrige bugs na compilação de expressões regulares sem distinção entre maiúsculas e minúsculas com classes de caracteres que contenham caracteres não BMP: o caractere maiúsculo não BMP foi ignorado e o sinalizador ASCII foi ignorado ao corresponder a um intervalo de caracteres cujo limite superior está além da região BMP.

  • gh-117378: Corrigido o processo de forkserver do método de início multiprocessing "forkserver" para herdar corretamente o sys.path do pai durante a importação de módulos multiprocessing.set_forkserver_preload() da mesma maneira que sys.path é configurado em workers antes de executar itens de trabalho.

    This bug caused some forkserver module preloading to silently fail to preload. This manifested as a performance degradation in child processes when the sys.path was required due to additional repeated work in every worker.

    Também poderia ter um efeito colateral de "" permanecer em sys.path durante importações de pré-carregamento do forkserver em vez do caminho absoluto de os.getcwd() no momento da importação de multiprocessamento usado no worker sys.path.

    As diferenças de sys.path entre as fases no processo filho poderiam ter causado o pré-carregamento para importar coisas incorretas do local errado. Não temos conhecimento de que isso realmente tenha acontecido na prática.

  • gh-125679: Os valores de multiprocessing.Lock e multiprocessing.RLock repr não dizem mais “unknown” no macOS.

  • gh-126476: Levanta calendar.IllegalMonthError (agora uma subclasse de IndexError) para calendar.month() quando o mês de entrada não está correto.

  • gh-126489: A implementação Python de pickle não chama mais pickle.Pickler.persistent_id() para o resultado de persistent_id().

  • gh-126451: Register the contextvars.Context type to collections.abc.Mapping.

  • gh-126175: Add msg, doc, pos, lineno and colno attributes to tomllib.TOMLDecodeError. Deprecate instantiating with free-form arguments.

  • gh-89416: Add RFC 9559 MIME types for Matroska audiovisual container formats. Patch by Hugo van Kemenade.

  • gh-126417: Register the multiprocessing.managers.DictProxy and multiprocessing.managers.ListProxy types in multiprocessing.managers to collections.abc.MutableMapping and collections.abc.MutableSequence, respectively.

  • gh-126390: Add support for returning intermixed options and non-option arguments in order in getopt.gnu_getopt().

  • gh-126374: Add support for options with optional arguments in the getopt module.

  • gh-126363: Speed up pattern parsing in pathlib.Path.glob() by skipping creation of a pathlib.Path object for the pattern.

  • gh-126353: asyncio.get_event_loop() now does not implicitly creates an event loop. It now raises a RuntimeError if there is no set event loop. Patch by Kumar Aditya.

  • gh-126313: Corrige um problema em curses.napms() quando curses.initscr() ainda não foi chamado. Patch por Bénédikt Tran.

  • gh-126303: Corrige serializar com pickle e cópia de objetos os.sched_param.

  • gh-126138: Corrige uma falha de uso após liberação em objetos asyncio.Task cuja corrotina subjacente produz um objeto que implementa um __getattribute__() maligno. Patch por Nico Posada.

  • gh-120057: Replace the os.environ.refresh() method with a new os.reload_environ() function. Patch by Victor Stinner.

  • gh-126220: Corrige falha em cProfile.Profile e _lsprof.Profiler quando seus retornos de chamada eram chamados diretamente com 0 argumentos.

  • gh-126212: Corrige problema em que urllib.request.pathname2url() e url2pathname() removiam barras de caminhos de unidade DOS do Windows e URLs.

  • gh-126223: Levanta UnicodeEncodeError em vez de um SystemError ao chamar _interpreters.create() com um caractere Unicode inválido.

  • gh-126205: Corrige o problema em que urllib.request.pathname2url() gerava URLs começando com quatro barras (em vez de duas) quando recebia um caminho UNC do Windows.

  • gh-126156: Improved performances of creating Morsel objects by a factor of 3.8x.

  • gh-126105: Corrige uma falha em ast quando o atributo ast.AST._fields é excluído.

  • gh-126106: Corrige uma possível desreferência de ponteiro NULL em ssl.

  • gh-126080: Corrige uma falha de uso após liberação em objetos asyncio.Task para os quais o loop de eventos subjacente implementa um __getattribute__() maligno. Relatado por Nico-Posada. Patch por Bénédikt Tran.

  • gh-125322: Correct detection of complex numbers support in libffi.

  • gh-126083: Corrige um vazamento de referência em objetos asyncio.Task ao reinicializar o mesmo objeto com um contexto não None. Patch por Nico Posada.

  • gh-126068: Fix exceptions in the argparse module so that only error messages for ArgumentError and ArgumentTypeError are now translated. ArgumentError is now only used for command line errors, not for logical errors in the program. TypeError is now raised instead of ValueError for some logical errors.

  • gh-125413: Add pathlib.Path.scandir() method to efficiently fetch directory children and their file attributes. This is a trivial wrapper of os.scandir().

  • gh-125984: Corrige falhas de uso após liberação em objetos asyncio.Future para os quais o laço de eventos subjacente implementa um __getattribute__() maligno. Relatado por Nico-Posada. Patch por Bénédikt Tran.

  • gh-125926: Fix urllib.parse.urljoin() for base URI with undefined authority. Although RFC 3986 only specify reference resolution for absolute base URI, urljoin() should continue to return sensible result for relative base URI.

  • gh-125969: Corrige uma falha fora dos limites quando um asyncio.loop.call_soon() maligno altera o comprimento da lista de retornos de chamada internos. Patch por Bénédikt Tran.

  • gh-125966: Corrige uma falha de uso após liberação em asyncio.Future.remove_done_callback(). Patch por Bénédikt Tran.

  • gh-125789: Corrige possível falha ao alterar a lista de retornos de chamada retornados por asyncio.Future._callbacks. Agora ele sempre retorna uma nova cópia na implementação C _asyncio. Patch por Kumar Aditya.

  • gh-126916: Allow the initial parameter of functools.reduce() to be passed as a keyword argument. Patch by Sayandip Dutta.

  • gh-124452: Corrige um problema em email.policy.EmailPolicy.header_source_parse() e email.policy.Compat32.header_source_parse() que introduziam espaços em branco iniciais espúrios em valores de cabeçalho quando o cabeçalho incluía um caractere de nova linha após o delimitador de nome do cabeçalho (:) e antes do valor.

  • gh-117941: argparse.BooleanOptionalAction now rejects option names starting with --no-.

  • gh-125884: Corrige o bug para pdb onde ele não pode definir pontos de interrupção em funções com certas anotações.

  • gh-125355: Corrige vários bugs em argparse.ArgumentParser.parse_intermixed_args().

    • O analisador não muda mais temporariamente durante a análise.

    • Os valores padrão não são processados duas vezes.

    • Os grupos mutuamente exclusivos obrigatórios contendo argumentos posicionais agora são suportados.

    • O relatório de argumentos ausentes agora inclui os nomes de todos os argumentos posicionais e opcionais necessários.

    • Opções desconhecidas podem ser misturadas com argumentos posicionais em parse_known_intermixed_args().

  • gh-125767: super objects are now pickleable and copyable.

  • gh-124969: locale.nl_langinfo(locale.ALT_DIGITS) now returns a string again. The returned value consists of up to 100 semicolon-separated symbols.

  • gh-84850: Remove URLopener and FancyURLopener classes from urllib.request. They had previously raised DeprecationWarning since Python 3.3.

  • gh-125666: Evita a saída do interpretador se um byte nulo for fornecido como entrada no novo REPL.

  • gh-125710: [Enum] corrige comparações hasheável<->não-hasheável para valores de membros

  • gh-125631: Restaura a capacidade de definir atributos persistent_id e persistent_load de instâncias das classes Pickler e Unpickler no módulo pickle.

  • gh-125378: Corrige o bug em pdb onde após um comando multilinha, uma linha vazia repete a primeira linha do comando multilinha, em vez do comando completo.

  • gh-125682: Rejeita dígitos não ASCII na implementação Python de json.loads() em conformidade com a especificação JSON.

  • gh-125660: Rejeita escapes unicode inválidos para implementação Python de json.loads().

  • gh-52551: Use wcsftime() to implement time.strftime() on Windows.

  • gh-125259: Corrige a lógica de remoção de notas para erros lançados na inicialização de enumeração.

  • gh-125633: Add function inspect.ispackage() to determine whether an object is a package or not.

  • gh-125614: In the FORWARDREF format of annotationlib, fix bug where nested expressions were not returned as annotationlib.ForwardRef format.

  • gh-125590: Permite que FrameLocalsProxy exclua e remova se a chave não for uma variável rápida.

  • gh-125600: Only show stale code warning in pdb when we display source code.

  • gh-125542: Deprecate passing keyword-only prefix_chars argument to argparse.ArgumentParser.add_argument_group().

  • gh-125541: Pressing Ctrl-C while blocked in threading.Lock.acquire(), threading.RLock.acquire(), and threading.Thread.join() now interrupts the function call and raises a KeyboardInterrupt exception on Windows, similar to how those functions behave on macOS and Linux.

  • gh-125519: Melhora o traceback se importlib.reload() for chamado com um objeto que não seja um módulo. Patch por Alex Waygood.

  • gh-125451: Corrige um impasse quando concurrent.futures.ProcessPoolExecutor desliga simultaneamente com um erro ao alimentar um trabalho para um processo de trabalho.

  • gh-125115: Corrige um bug em pdb onde argumentos começando com - não podem ser passados para o script depurado.

  • gh-125398: Corrige a conversão do caminho VIRTUAL_ENV no script activate em venv ao executar no Git Bash para Windows.

  • gh-125245: Corrige condição de corrida ao importar collections.abc, que poderia retornar incorretamente um módulo vazio.

  • gh-52551: Corrige problemas de codificação em time.strftime(), o método strftime() das classes datetime datetime, date e time e a formatação dessas classes. Caracteres não codificáveis no localidade atual agora são aceitáveis na string de formato. Pares substitutos e sequência de bytes codificados por surrogatescape não são mais recombinados. O caractere nulo incorporado não termina mais a string de formato.

  • gh-124984: Corrige segurança de thread em ssl na construção com threads livres. As operações OpenSSL agora são protegidas por uma trava por objeto.

  • gh-124651: Coloca corretamente entre aspas as strings template em scripts de ativação venv.

  • gh-124694: We’ve added concurrent.futures.InterpreterPoolExecutor, which allows you to run code in multiple isolated interpreters. This allows you to circumvent the limitations of CPU-bound threads (due to the GIL). Patch by Eric Snow.

    This addition is unrelated to PEP 734.

  • gh-58032: Deprecate the argparse.FileType type converter.

  • gh-99749: Adds a feature to optionally enable suggestions for argument choices and subparser names if mistyped by the user.

  • gh-58956: Corrigido um bug em pdb onde às vezes o ponto de interrupção não disparava se ele fosse definido em uma função que já está na pilha de chamadas.

  • gh-124111: The tkinter module can now be built to use either the new version 9.0.0 of Tcl/Tk or the latest release 8.6.15 of Tcl/Tk 8. Tcl/Tk 9 includes many improvements, both to the Tcl language and to the appearance and utility of the graphical user interface provided by Tk.

  • gh-80958: unittest discovery supports PEP 420 namespace packages as start directory again.

  • gh-123370: Corrige a tela que não limpa após executar o relógio turtledemo.

  • gh-89083: Add uuid.uuid8() for generating UUIDv8 objects as specified in RFC 9562. Patch by Bénédikt Tran

  • gh-122549: Add platform.invalidate_caches() to invalidate cached results.

  • gh-120754: Atualiza chamadas read ilimitadas em zipfile para especificar um size explícito, colocando um limite na quantidade de dados que eles podem ler. Isso também atualiza o tratamento em torno do tamanho máximo de comentário do ZIP para corresponder ao padrão em vez de ler comentários que são um byte muito longos.

  • gh-121267: Improve the performance of tarfile when writing files, by caching user names and group names.

  • gh-70764: Corrigido um problema em que inspect.getclosurevars() classificaria incorretamente um nome de atributo como uma variável global quando o nome existe tanto como um nome de atributo quanto como uma variável global.

  • gh-118289: posixpath.realpath() agora levanta NotADirectoryError quando o modo strict está habilitado e um caminho sem diretório com uma barra final é fornecido.

  • gh-119826: Sempre retorna um caminho absoluto para os.path.abspath() no Windows.

  • gh-97850: Remove deprecated pkgutil.get_loader() and pkgutil.find_loader().

  • gh-118986: Add socket.IPV6_RECVERR constant (available since Linux 2.2).

  • gh-116897: Accepting objects with false values (like 0 and []) except empty strings, byte-like objects and None in urllib.parse functions parse_qsl() and parse_qs() is now deprecated.

  • gh-101955: Corrige SystemError ao corresponder ao padrão de expressão regular contendo alguma combinação de quantificador possessivo, alternativo e grupo de captura.

  • gh-71936: Corrigir uma condição de corrida em multiprocessing.pool.Pool.

  • bpo-46128: Remove quadros de pilha unittest.IsolatedAsyncioTestCase de stacktraces relatados.

  • gh-84852: Add MIME types for MS Embedded OpenType, OpenType Layout, TrueType, WOFF 1.0 and 2.0 fonts. Patch by Sahil Prajapati and Hugo van Kemenade.

Documentação

  • gh-126622: Adicionadas páginas de rascunho para módulos removidos explicando sua remoção, onde encontrar substituições e links para a última versão do Python que os suportava. Contribuição de Ned Batchelder.

  • gh-125277: Exige Sphinx 7.2.6 ou posterior para construir a documentação do Python. Patch por Adam Turner.

  • gh-60712: Inclui o tipo object nas listas de tipos documentados. Alteração por Furkan Onder e Martin Panter.

Núcleo e embutidos

  • gh-126795: Increase the threshold for JIT code warmup. Depending on platform and workload, this can result in performance gains of 1-9% and memory savings of 3-5%.

  • gh-126341: Agora ValueError é levantada em vez de SystemError ao tentar iterar sobre um objeto memoryview liberado.

  • gh-126688: Corrige uma falha ao chamar os.fork() em alguns sistemas operacionais, incluindo SerenityOS.

Biblioteca

  • gh-126066: Corrige importlib para não gravar arquivos .pyc incompletos quando um ulimit ou algum outro mecanismo do sistema operacional estiver impedindo que a gravação seja feita completamente.

Núcleo e embutidos

  • gh-126222: Do not include count of “peek” items in _PyUop_num_popped. This ensures that the correct number of items are popped from the stack when a micro-op exits with an error.

  • gh-126366: Fix crash when using yield from on an object that raises an exception in its __iter__.

Biblioteca

  • gh-126209: Fix an issue with skip_file_prefixes parameter which resulted in an inconsistent behaviour between the C and Python implementations of warnings.warn(). Patch by Daehee Kim.

Núcleo e embutidos

  • gh-126312: Corrige travamento durante a coleta de lixo em um objeto congelado por gc.freeze() na construção com threads livres.

  • gh-103951: Relax optimization requirements to allow fast attribute access to module subclasses.

  • gh-126072: Following gh-126101, for Objetos código like lambda, annotation and type alias, we no longer add None to its co_consts.

  • gh-126195: Improve JIT performance by 1.4% on macOS Apple Silicon by using platform-specific memory protection APIs. Patch by Diego Russo.

  • gh-126139: Fornece melhor localização de erro ao tentar usar uma instrução future com um recurso futuro desconhecido.

  • gh-126072: Add a new attribute in co_flags to indicate whether the first item in co_consts is the docstring. If a code object has no docstring, None will NOT be inserted.

  • gh-126076: Objetos realocados, como objetos tuple, bytes e str são rastreados corretamente por tracemalloc e seus ganchos associados. Patch por Pablo Galindo.

  • gh-90370: Avoid temporary tuple creation for vararg in argument passing with Argument Clinic generated code (if arguments either vararg or positional-only).

  • gh-126018: Corrige travamento em sys.audit() ao passar uma não string como primeiro argumento e o Python foi compilado no modo de depuração.

  • gh-126012: The memoryview type now supports subscription, making it a generic type.

  • gh-125837: Adds LOAD_SMALL_INT and LOAD_CONST_IMMORTAL instructions. LOAD_SMALL_INT pushes a small integer equal to the oparg to the stack. LOAD_CONST_IMMORTAL does the same as LOAD_CONST but is more efficient for immortal objects. Removes RETURN_CONST instruction.

  • gh-125942: No Android, a configuração errors de sys.stdout foi alterada de surrogateescape para backslashreplace.

  • gh-125859: Corrige uma falha na construção com threads livres quando gc.get_objects() ou gc.get_referrers() é chamado durante uma coleta de lixo em andamento.

  • gh-125868: It was possible in 3.14.0a1 only for attribute lookup to give the wrong value. This was due to an incorrect specialization in very specific circumstances. This is fixed in 3.14.0a2.

  • gh-125498: The JIT has been updated to leverage Clang 19’s new preserve_none attribute, which supports more platforms and is more useful than LLVM’s existing ghccc calling convention. This also removes the need to manually patch the calling convention in LLVM IR, simplifying the JIT compilation process.

  • gh-125703: Honra corretamente os ganchos tracemalloc em caminhos Py_DECREF especializados. Patch por Pablo Galindo

  • gh-125593: Usa cores para destacar locais de erro no traceback do grupo de exceções

  • gh-125017: Fix crash on certain accesses to the __annotations__ of staticmethod and classmethod objects.

  • gh-125588: The Python PEG generator can now use f-strings in the grammar actions. Patch by Pablo Galindo

  • gh-125444: Corrige instruções ilegais para arquiteturas Arm mais antigas. Patch por Diego Russo, testes de Ross Burton.

  • gh-118423: Add a new INSTRUCTION_SIZE macro to the cases generator which returns the current instruction size.

  • gh-125038: Corrige falha ao iterar sobre uma expressão geradora após alterações diretas em gi_frame.f_locals. Patch por Mikhail Efimov.

  • gh-124855: Don’t allow the JIT and perf support to be active at the same time. Patch by Pablo Galindo

  • gh-123714: Update JIT compilation to use LLVM 19

  • gh-123930: Melhora a mensagem de erro quando um script que faz “shadowing” de um módulo da biblioteca padrão faz com que ImportError seja levantada durante uma importação “from”. Da mesma forma, melhore a mensagem de erro quando um script que faz shadowing de um módulo de terceiros tenta importar um atributo desse módulo de terceiros enquanto ainda está inicializando.

  • gh-119793: The map() built-in now has an optional keyword-only strict flag like zip() to check that all the iterables are of equal length. Patch by Wannes Boeykens.

Biblioteca

  • gh-118950: Corrige o bug em que SSLProtocol.connection_lost não estava sendo chamado quando OSError era lançada na gravação no soquete.

  • gh-113570: Corrige um bug em reprlib.repr em que ele chamava incorretamente o método repr em tipos embutidos Python com shadowing.

API C

Construção

  • gh-126691: Removed the --with-emscripten-target configure flag. We unified the node and browser options and the same build can now be used, independent of target runtime.

  • gh-123877: Use wasm32-wasip1 as the target triple for WASI instead of wasm32-wasi. The latter will eventually be reclaimed for WASI 1.0 while CPython currently only supports WASI preview1.

  • gh-126458: Disable SIMD support for HACL under WASI.

  • gh-89640: Codifica a ordem de palavras float como little endian no WASM.

  • gh-126206: make clinic now runs Argument Clinic using the --force option, thus forcefully regenerating generated code.

  • gh-126187: Introduced Tools/wasm/emscripten.py to simplify doing Emscripten builds.

  • gh-124932: For cross builds, there is now support for having a different install prefix than the host_prefix used by getpath.py. This is set to / by default for Emscripten, on other platforms the default behavior is the same as before.

  • gh-125946: The minimum supported Android version is now 7.0 (API level 24).

  • gh-125940: A construção no Android agora oferece suporte a tamanhos de página de 16 KB.

  • gh-89640: Melhora a detecção da ordem de palavras flutuantes no Linux quando as otimizações de tempo de link estiverem habilitadas.

  • gh-124928: Emscripten builds now require node >= 18.

  • gh-115382: Corrige falhas de compilação cruzada quando o host e o SOABIs de destino correspondem.

Python 3.14.0 alpha 1

Data de lançamento: 2024-10-15

macOS

  • gh-124448: Atualiza o Tcl/Tk empacotado no instalador do macOS para 8.6.15.

  • gh-123797: Verifica a disponibilidade do tempo de execução da função ptsname_r no macOS.

  • gh-123418: Construção do instalador do macOS atualizada para usar o OpenSSL 3.0.15.

Windows

  • gh-124487: Increases Windows required OS and API level to Windows 10.

  • gh-124609: Corrige _Py_ThreadId para construções do Windows usando MinGW. Patch por Tony Roberts.

  • gh-124448: Tcl/Tk empacotado atualizado para 8.6.15.

  • gh-124254: Garante que binários experimentais de threads livres permaneçam instalados durante a atualização.

  • gh-123915: Garante que Tools\\msi\\buildrelease.bat use diretórios diferentes para compilações AMD64 e ARM64.

  • gh-123418: Construção do Windows atualizada para usar o OpenSSL 3.0.15.

  • gh-123476: Add support for socket.TCP_QUICKACK on Windows platforms.

  • gh-122573: A construção do Windows do CPython agora requer 3.10 ou mais recente.

  • gh-100256: mimetypes não falha mais quando encontra uma chave de registro inacessível.

  • gh-119679: Garante que bibliotecas de importação corretas sejam incluídas nas instalações do Windows.

  • gh-119690: Adiciona suporte a Unicode e corrige eventos de auditoria para _winapi.CreateNamedPipe.

  • gh-111201: Adiciona suporte para o novo pyrepl no Windows

  • gh-119070: Corrige o tratamento de py.exe de shebangs como /usr/bin/env python3.12, que eram interpretados anteriormente como python3.exe em vez de python3.12.exe.

  • gh-117505: Corrige um problema com o instalador do Windows não executando ensurepip em um ambiente totalmente isolado. Isso pode causar interações inesperadas com os pacotes do site do usuário.

  • gh-118209: Evita travamentos em mmap no Windows quando a memória mapeada estiver inacessível devido a erros do sistema de arquivos ou violações de acesso.

  • gh-79846: Faz com que ssl.create_default_context() ignore certificados inválidos no armazenamento de certificados do Windows

Ferramentas/Demos

  • gh-123418: Atualiza os fluxos de trabalho do GitHub CI para usar o OpenSSL 3.0.15 e multissltests para usar 3.0.15, 3.1.7 e 3.2.3.

Testes

  • gh-125041: Reativa testes ignorados para zlib na arquitetura s390x: ignora apenas verificações dos bytes compactados, que podem ser diferentes entre a implementação de software do zlib e a implementação acelerada por hardware.

  • gh-124378: Atualizado test_ttk para passar com Tcl/Tk 8.6.15.

  • gh-124213: Detect whether the test suite is running inside a systemd-nspawn container with --suppress-sync=true option, and skip the test_os and test_mmap tests that are failing in this scenario.

  • gh-124190: Add capability to ignore entire files or directories in check warning CI tool

  • gh-121921: Update Lib/test/crashers/bogus_code_obj.py so that it crashes properly again.

  • gh-112301: Add tooling to check for changes in compiler warnings. Patch by Nate Ohlson.

  • gh-59022: Adiciona testes para pkgutil.extend_path(). Patch por Andreas Stocker.

  • gh-99242: os.getloadavg() pode levantar OSError ao executar testes de regressão sob certas condições (por exemplo, chroot). Este erro agora é capturado e ignorado, pois o relatório da média de carga é opcional.

  • gh-121084: Corrige vazamentos aleatórios de test_typing. Limpa caches ABC de tipagem ao executar testes para refleaks (opção -R): chama _abc_caches_clear() em classes abstratas de tipagem e suas subclasses. Patch por Victor Stinner.

  • gh-121160: Adiciona um teste para readline.set_history_length(). Observe que este teste pode falhar em bibliotecas readline.

  • gh-121200: Corrige test_expanduser_pwd2() de test_posixpath. Chama getpwnam() para obter pw_dir, pois pode ser diferente de getpwall() pw_dir. Patch por Victor Stinner.

  • gh-121188: Ao criar o arquivo XML JUnit, o regrtest agora escapa caracteres inválidos em XML, como o caractere de controle chr(27) usado em sequências de escape ANSI. Patch por Victor Stinner.

  • gh-120801: Cleaned up fixtures for importlib.metadata tests and consolidated behavior with ‘test.support.os_helper’.

  • gh-119727: Adiciona a opção de linha de comando --single-process ao executor de testes Python (regrtest). Patch por Victor Stinner.

  • gh-119273: Python test runner no longer runs tests using TTY (ex: test_ioctl) in a process group (using setsid()). Previously, tests using TTY were skipped. Patch by Victor Stinner.

  • gh-119050: Executor de teste regrtest: Adiciona suporte XML ao verificador de reflexos (opção -R). Patch de Victor Stinner.

  • gh-101525: Ignora test_gdb se o binário for realocado pelo BOLT. Patch por Donghee Na.

  • gh-107562: Test certificates have been updated to expire far in the future. This allows testing Y2038 with system time set to after that, so that actual Y2038 issues can be exposed, and not masked by expired certificate errors.

Segurança

  • gh-125140: Remove o diretório atual de sys.path ao usar PyREPL.

  • gh-123678: Atualiza o libexpat para 2.6.3

  • gh-112301: Enable compiler options that warn of potential security vulnerabilities.

  • gh-122792: Alterado ipaddress.IPv6Address mapeado para IPv4 para usar consistentemente o valor do endereço IPv4 mapeado para decidir propriedades. Propriedades que têm seu comportamento corrigido são is_multicast, is_reserved, is_link_local, is_global e is_unspecified.

  • gh-112301: Add ability to ignore warnings per file with warning count in warning checking tooling. Patch by Nate Ohlson.

  • gh-112301: Add macOS warning tracking to warning check tooling. Patch by Nate Ohlson.

  • gh-122133: Autentica a conexão de soquete para o fallback socket.socketpair() em plataformas onde AF_UNIX não está disponível, como o Windows.

    Patch por Gregory P. Smith <greg@krypto.org> e Seth Larson <seth@python.org>. Reportado por Ellie <el@horse64.org>

  • gh-121957: Corrigidos eventos de auditoria ausentes no uso interativo do Python, agora também sendo acionados corretamente para python -i, bem como para python -m asyncio. Os eventos em questão são cpython.run_stdin e cpython.run_startup.

  • gh-112301: Enable runtime protections for glibc to abort execution when unsafe behavior is encountered, for all platforms except Windows.

  • gh-121285: Remove o backtracking da análise de cabeçalho do arquivo tar para hdrcharset, PAX e cabeçalhos esparsos GNU.

  • gh-112301: Add default compiler options to improve security. Enable -Wimplicit-fallthrough, -fstack-protector-strong, -Wtrampolines.

  • gh-118773: Corrige a criação de ACLs em os.mkdir() no Windows para funcionar corretamente em máquinas que não falam inglês.

  • gh-118486: os.mkdir() no Windows agora aceita o modo de 0o700 para restringir o novo diretório ao usuário atual. Isso corrige CVE 2024-4030 afetando tempfile.mkdtemp() em cenários onde o diretório temporário base é mais permissivo do que o padrão.

Biblioteca

  • gh-125422: Corrige o bug onde pdb e bdb podem entrar no quadro do chamador inferior.

  • gh-100141: Corrige o bug onde pdb ficará preso em um laço infinito ao depurar um arquivo vazio.

  • gh-53203: Corrige time.strptime() para os formatos %c, %x e %X em muitos locais que usam dígitos não ASCII, como persa, birmanês, odia e shan.

  • gh-125206: Workaround for old libffi versions is added. Module ctypes supports double complex only with libffi >= 3.3.0. Patch by Mikhail Efimov.

  • gh-89967: Make WeakKeyDictionary and WeakValueDictionary safe against concurrent mutations from other threads. Patch by Kumar Aditya.

  • gh-125260: The gzip.compress() mtime parameter now defaults to 0 for reproducible output. Patch by Bernhard M. Wiedemann and Adam Turner.

  • gh-125243: Corrige corrida de dados ao criar objetos zoneinfo.ZoneInfo na construção com threads livres.

  • gh-125254: Corrige um bug em que ArgumentError inclui a opção ambígua incorreta em argparse.

  • gh-125235: Mantém os caminhos TCL tkinter em venv apontando para a instalação base no Windows.

  • gh-61011: Corrige herança de grupos mutuamente exclusivos aninhados do analisador pai em argparse.ArgumentParser. Anteriormente, todos os grupos mutuamente exclusivos aninhados perdiam sua conexão com o grupo que os continha e eram exibidos como pertencentes diretamente ao analisador.

  • gh-125118: Não copia valores arbitrários para _Bool no módulo struct.

  • gh-125069: Corrige um problema em que fornecer um objeto pathlib.PurePath como um argumento inicializador para um segundo objeto PurePath com um parser diferente resultava em argumentos para o inicializador do objeto anterior sendo unidos pelo analisador do objeto posterior.

  • gh-125096: Se a variável de ambiente PYTHON_BASIC_REPL estiver definida, o módulo site não importa mais o módulo _pyrepl. Além disso, o módulo site agora respeita as opções de linha de comando -E e -I: ignore PYTHON_BASIC_REPL neste caso. Patch por Victor Stinner.

  • gh-124969: Fix locale.nl_langinfo(locale.ALT_DIGITS). Now it returns a tuple of up to 100 strings (an empty tuple on most locales). Previously it returned the first item of that tuple or an empty string.

  • gh-124960: Corrige suporte para o sinalizador future barry_as_FLUFL no novo REPL.

  • gh-69998: Fix locale.nl_langinfo() in case when different categories have different locales. The function now sets temporarily the LC_CTYPE locale in some cases. This temporary change affects other threads.

  • gh-124958: Corrige refcycles em exceções levantadas de asyncio.TaskGroup e a implementação python de asyncio.Future

  • gh-53203: Corrige time.strptime() para os formatos %c e %x em muitos idiomas: árabe, bislama, bretão, bodo, cassubiano, chuvache, estoniano, francês, irlandês, ge’ez, gurajati, gaélico manx, hebraico, hindi, chhattisgarhi, crioulo haitiano, japonês, canarês, coreano, marata, malaio, norueguês, nynorsk, punjabi, rajasthani, tok pisin, iorubá, chinês yue, yau nungon e chinês.

  • gh-123961: Convert curses to multi-phase initialization (PEP 489), thereby fixing reference leaks at interpreter shutdown. Patch by Bénédikt Tran.

  • gh-124944: Add SO_ORIGINAL_DST to the socket module.

  • gh-117151: The default buffer size used by shutil.copyfileobj() has been increased from 64k to 256k on non-Windows platforms. It was already larger on Windows.

  • gh-90102: Skip the isatty system call during open() when the file is known to not be a character device. This provides a slight performance improvement when reading whole files.

  • gh-124917: Permite chamar os.path.exists() e os.path.lexists() com argumentos nomeados no Windows. Corrige uma regressão em 3.13.0.

  • gh-65865: argparse now raises early error for invalid help arguments to add_argument(), add_subparsers() and add_parser().

  • gh-124653: Corrige a detecção da API de fila mínima necessária pelo módulo logging. Patch por Bénédikt Tran.

  • gh-91818: The CLI of many modules (ast, ensurepip, json, pdb, sqlite3, tokenize, venv) now uses the actual executable name instead of simply “python” to display in the usage message.

  • gh-124858: Corrige ciclos de referência deixados em tracebacks em asyncio.open_connection() quando usado com happy_eyeballs_delay

  • gh-124390: Fixed AssertionError when using asyncio.staggered.staggered_race() with asyncio.eager_task_factory.

  • gh-85935: argparse.ArgumentParser.add_argument() now raises an exception if an action that does not consume arguments (like ‘store_const’ or ‘store_true’) or explicit nargs=0 are specified for positional arguments.

  • gh-124835: Make tomllib.loads() raise TypeError not AttributeError on bad input types that do not have the replace attribute. Improve error message when bytes is received.

  • gh-124693: Fix a bug where argparse doesn’t recognize negative complex numbers or negative numbers using scientific notation.

  • gh-124787: Fix typing.TypeAliasType with incorrect type_params argument. Now it raises a TypeError when a type parameter without a default follows one with a default, and when an entry in the type_params tuple is not a type parameter object.

  • gh-66436: Improved prog default value for argparse.ArgumentParser. It will now include the name of the Python executable along with the module or package name, or the path to a directory, ZIP file, or directory within a ZIP file if the code was run that way.

  • gh-116850: Corrige argparse para espaços de nomes com dict não diretamente gravável (por exemplo, classes).

  • gh-101552: Add an annoation_format parameter to inspect.signature(). Add an quote_annotation_strings parameter to inspect.Signature.format(). Use the new functionality to improve the display of annotations in signatures in pydoc. Patch by Jelle Zijlstra.

  • gh-58573: Corrige conflitos entre opções longas abreviadas no analisador pai e subanalisadores em argparse.

  • gh-124594: Todos os prompts REPL asyncio são executados no mesmo context. Contribuição de Bartosz Sławecki.

  • gh-61181: Corrige suporte de choices com valor de string em argparse. Substrings da string especificada não são mais considerados valores válidos.

  • gh-116750: Provide sys.monitoring.clear_tool_id() to unregister all events and callbacks set by the tool.

  • gh-124552: Improve the accuracy of bdb’s check for the possibility of breakpoint in a frame. This makes it possible to disable unnecessary events in functions.

  • gh-124538: Corrige falha ao usar gc.get_referents() em um objeto cápsula.

  • gh-80259: Corrige suporte de argparse de argumentos posicionais com nargs='?', default=argparse.SUPPRESS e type especificado.

  • gh-120378: Corrige uma falha relacionada a um estouro de inteiro em curses.resizeterm() e curses.resize_term().

  • gh-124498: Corrige typing.TypeAliasType para não ser genérico, quando type_params é uma tupla vazia.

  • gh-53834: Fix support of arguments with choices in argparse. Positional arguments with nargs equal to '?' or '*' no longer check default against choices. Optional arguments with nargs equal to '?' no longer check const against choices.

  • gh-123884: Corrige bug no tratamento de itertools.tee() de outras entradas tee (um tee em um tee). A saída agora tem os prometidos n novos iteradores independentes. Anteriormente, o primeiro iterador era idêntico (não independente) ao iterador de entrada. Isso às vezes dava resultados surpreendentes.

  • gh-123017: Devido a resultados não confiáveis em alguns dispositivos, time.strftime() não aceita mais anos negativos no Android.

  • gh-123014: os.pidfd_open() e signal.pidfd_send_signal() agora estão indisponíveis ao construir em níveis de API do Android mais antigos que 31, pois as chamadas de sistema subjacentes podem causar uma falha.

  • gh-124176: Add support for dataclasses.dataclass() in unittest.mock.create_autospec(). Now create_autospec will check for potential dataclasses and use dataclasses.fields() function to retrieve the spec information.

  • gh-124345: argparse supports abbreviated single-dash long options separated by = from its value.

  • gh-124400: Fixed a pdb bug where until has no effect when it appears in a commands sequence. Also avoid printing the frame information at a breakpoint that has a command list containing a command that resumes execution.

  • gh-90562: Modify dataclasses to support zero-argument super() when slots=True is specified. This works by modifying all references to __class__ to point to the newly created class.

  • gh-104860: Corrigido a falta de permissão de abreviação de opções longas de traço simples em argparse com allow_abbrev=False.

  • gh-63143: Corrigida a análise de argumentos mutuamente exclusivos em argparse. Argumentos com o valor idêntico ao valor padrão (por exemplo, booleanos, inteiros pequenos, strings vazias ou de 1 caractere) não são mais considerados “não presentes”.

  • gh-72795: Argumentos posicionais com nargs igual a '*' ou argparse.REMAINDER não são mais necessários. Isso permite usar argumento posicional com nargs='*' e sem default em grupo mutuamente exclusivo e melhora a mensagem de erro sobre argumentos necessários.

  • gh-59317: Corrige análise de argumento posicional com nargs igual a '?' ou '*' se for precedido por uma opção e outro argumento posicional.

  • gh-100980: The _fields_ attribute of ctypes.Structure and Union is no longer set if the setattr operation raises an error.

  • gh-53780: argparse agora ignora o primeiro "--" (traço duplo) entre uma opção e um comando.

  • gh-124217: Adicionar bloco IPv6 reservado do RFC 9637 3fff::/20 no módulo ipaddress.

  • gh-111513: Improve the error message that may be raised by datetime.date.fromtimestamp().

  • gh-124248: Corrige possível falha ao usar struct para processar campos ‘Pascal string’ de largura zero (0p).

  • gh-81691: Corrige manipulação de múltiplos "--" (traços duplos) em argparse. Apenas o primeiro foi removido, todos os subsequentes agora são tomados literalmente.

  • gh-87041: Corrige um bug em argparse onde a ajuda de argumento de sub-analisador longa é indentada incorretamente.

  • gh-84559: The default multiprocessing start method on Linux and other POSIX systems has been changed away from often unsafe "fork" to "forkserver" (when the platform supports sending file handles over pipes as most do) or "spawn". Mac and Windows are unchanged as they already default to "spawn".

  • gh-124212: Corrige variável inválida em venv manipulação de link simbólico com falha no Windows

  • gh-124171: Adiciona solução alternativa para implementações quebradas de fmod() no Windows, que perdem o sinal de zero (por exemplo, fmod(-10, 1) retorna 0.0). Patch por Sergey B Kirpichev.

  • gh-123978: Remove time.thread_time() e time.thread_time_ns() quebrados no NetBSD.

  • gh-123934: Fix unittest.mock.MagicMock resetting magic methods return values after .reset_mock(return_value=True) was called.

  • gh-124016: Update unicodedata database to Unicode 16.0.0.

  • gh-123968: Corrige a interface de linha de comando para o módulo random para selecionar floats entre 0 e N, não 1 e N.

  • gh-123945: Fix a bug where argparse doesn’t recognize negative numbers with underscores

  • gh-123935: Corrige detecção de slots pai para dataclasses que herdam de classes com __dictoffset__.

  • gh-123892: Adicionar "_wmi" a sys.stdlib_module_names. Patch por Victor Stinner.

  • gh-84808: Fix error handling in socket method connect_ex() on platforms where errno can be negative.

  • gh-123756: Added a new argument mode to pdb.Pdb. Only allow pdb from command line to use restart command.

  • gh-122765: Corrige erros de aspas desbalanceadas que ocorrem quando activate.csh em venv era carregado com um prompt personalizado contendo aspas desemparelhadas ou novas linhas.

  • gh-123657: Corrige o travamento e o vazamento de memória em decimal.getcontext(). Ele travava ao usar um contexto local de thread por --with-decimal-contextvar=no.

  • gh-123339: Corrige inspect.getsource() para classes nos módulos collections.abc e decimal (para implementação Python pura). inspect.getcomments() agora levanta OSError em vez de IndexError se o valor __firstlineno__ para uma classe estiver fora dos limites.

  • gh-123374: Remove check for redefined memo entry in pickletools.dis().

  • gh-123504: Fixed reference leak in the finalization of tkinter.

  • gh-123430: Pages generated by the http.server module allow the browser to apply its default dark mode.

  • gh-123446: Fix empty function name in TypeError when csv.reader(), csv.writer(), or csv.register_dialect() are used without the required args.

  • gh-123448: Corrigido vazamento de memória de typing.NoDefault movendo-o para o vetor de tipos estáticos.

  • gh-123409: Corrige a saída de ipaddress.IPv6Address.reverse_pointer de acordo com RFC 3596, §2.5. Patch por Bénédikt Tran.

  • gh-123089: Make weakref.WeakSet safe against concurrent mutations while it is being iterated. Patch by Kumar Aditya.

  • gh-123363: Show string value of CONTAINS_OP oparg in dis output. Patch by Alexandr153.

  • gh-123341: Add __class_getitem__() to tkinter.Event for type subscript support at runtime. Patch by Adonis Rakateli.

  • gh-123340: Show string value of IS_OP oparg in dis output.

  • gh-119518: Speed up normalization of pathlib.PurePath and Path objects by not interning string parts.

  • gh-123270: Aplicada uma correção mais cirúrgica para payloads malformados em zipfile.Path causando loops infinitos (gh-122905) sem quebrar o conteúdo usando caracteres legítimos.

  • gh-73991: Add pathlib.Path.copy_into() and move_into(), which copy and move files and directories into existing directories.

  • gh-123228: Corrige tipo de retorno para _pyrepl.readline._ReadlineWrapper.get_line_buffer() para ser str(). Patch por Sergey B Kirpichev.

  • gh-123240: Levanta eventos de auditoria para input() no novo REPL.

  • gh-76960: Fix urllib.parse.urljoin() and urllib.parse.urldefrag() for URIs containing empty components. For example, urljoin() with relative reference “?” now sets empty query and removes fragment. Preserve empty components (authority, params, query, fragment) in urljoin(). Preserve empty components (authority, params, query) in urldefrag().

  • gh-116810: Resolve um vazamento de memória introduzido no ssl do CPython 3.10 quando a propriedade ssl.SSLSocket.session era acessada. Acelera o acesso de leitura e gravação à referida propriedade ao não clonar mais objetos de sessão desnecessariamente por meio de serialização.

  • gh-123243: Corrige vazamento de memória em _decimal.

  • gh-122546: Usar consistentemente o mesmo nome de arquivo para diferentes exceções no novo repl. Patch por Sergey B Kirpichev.

  • gh-123213: xml.etree.ElementTree.Element.extend() and Element assignment no longer hide the internal exception if an erroneous generator is passed. Patch by Bar Harel.

  • gh-85110: Preserva caminho relativo em URL sem netloc em urllib.parse.urlunsplit() e urllib.parse.urlunparse().

  • gh-123165: Add support for rendering Positions in dis.

  • gh-122909: In urllib.request when URLError is raised opening an ftp URL, the exception argument is now consistently a string. Earlier versions passed either a string or an ftplib exception instance as the argument to URLError.

  • gh-123084: Deprecate shutil.ExecError, which hasn’t been raised by any shutil function since Python 3.4. It’s now an alias for RuntimeError.

  • gh-123085: In a bare call to importlib.resources.files(), ensure the caller’s frame is properly detected when importlib.resources is itself available as a compiled module only (no source).

  • gh-123067: Corrige complexidade quadrática na análise de valores de cookies entre aspas " com contrabarras por http.cookies.

  • gh-123049: Add support for UNNAMED_SECTION in configparser.ConfigParser.add_section().

  • gh-121735: Ao trabalhar com arquivos zip, importlib.resources agora honra corretamente referências adjacentes ao módulo (por exemplo, files(pkg.mod) e não apenas files(pkg)).

  • gh-122981: Corrige inspect.getsource() para classes geradas com classes base Python (por exemplo, enums).

  • gh-122903: zipfile.Path.glob agora corresponde corretamente aos diretórios em vez de omiti-los silenciosamente.

  • gh-122905: Objetos zipfile.Path agora sanitizam nomes do arquivo zip.

  • gh-122873: Enable json module to work as a script using the -m switch: python -m json. See the JSON command-line interface documentation. Patch by Trey Hunner.

  • gh-122858: Deprecate asyncio.iscoroutinefunction() in favor of inspect.iscoroutinefunction().

  • gh-116263: logging.handlers.RotatingFileHandler não substitui mais arquivos de log vazios.

  • gh-105376: Restaura o método descontinuado warn() do logging. Ele foi removido no Python 3.13 alpha 1. Mantém o método descontinuado warn() no Python 3.13. Patch por Victor Stinner.

  • gh-122311: Improve errors in the pickle module. PicklingError is now raised more often instead of UnicodeEncodeError, ValueError and AttributeError, and the original exception is chained to it. Improve and unify error messages in Python and C implementations.

  • gh-122744: Atualiza a versão do pip empacotado no ensurepip para a versão 24.2.

  • gh-118761: Improve import time of pprint by around seven times. Patch by Hugo van Kemenade.

  • gh-118974: Add decorator parameter to dataclasses.make_dataclass() to customize the functional creation of dataclasses.

  • gh-118814: Corrige o construtor typing.TypeVar quando o nome for passado como argumento nomeado.

  • gh-122637: Adjust cmath.tanh(nanj) and cmath.tanh(infj) for recent C standards.

  • gh-122478: Remove internal frames from tracebacks shown in code.InteractiveInterpreter with non-default sys.excepthook(). Save correct tracebacks in sys.last_traceback and update __traceback__ attribute of sys.last_value and sys.last_exc.

  • gh-116622: No Android, as constantes FICLONE e FICLONERANGE não são mais expostas por fcntl, pois esses ioctls são bloqueados pelo SELinux.

  • gh-82378: Garante que o novo REPL interprete sys.tracebacklimit da mesma forma que o REPL clássico.

  • gh-122334: Corrige o travamento ao importar ssl após a reinicialização do interpretador principal.

  • gh-122459: Optimize pickling by name objects without the __module__ attribute.

  • gh-87320: Em code.InteractiveInterpreter, trata exceções causadas pela chamada de um sys.excepthook() não padrão. Antes, a exceção era apresentada para o chamador, encerrando o REPL.

  • gh-122272: On some platforms such as Linux, year with century was not 0-padded when formatted by strftime() with C99-specific specifiers '%C' or '%F'. The 0-padding behavior is now guaranteed when the format specifiers '%C' and '%F' are supported by the C library. Patch by Ben Hsing

  • gh-122400: Lida com ValueErrors levantados por os.stat() em filecmp.dircmp e filecmp.cmpfiles(). Patch por Bénédikt Tran.

  • gh-122311: Corrige algumas mensagens de erro em pickle.

  • gh-121650: Cabeçalhos email com quebras de linha incorporadas agora são citados na saída. O generator agora se recusará a serializar (escrever) cabeçalhos que são dobrados ou delimitados de forma insegura; consulte verify_generated_headers. (Contribuição de Bas Bloemsaat e Petr Viktorin em gh-121650.)

  • gh-122332: Corrigido segfault com asyncio.Task.get_coro() ao usar uma fábrica de tarefas ansiosa.

  • gh-105733: a função ctypes.ARRAY() agora está suavemente descontinuada: ela não emite mais avisos de descontinuação e não está programada para remoção.

  • gh-122213: Add notes for pickle serialization errors that allow to identify the source of the error.

  • gh-119180: As part of PEP 749, add the following attributes for customizing evaluation of annotation scopes:

  • gh-119180: Fix handling of classes with custom metaclasses in annotationlib.get_annotations.

  • gh-122170: Lida com ValueErrors levantadas por os.stat() em linecache. Patch por Bénédikt Tran.

  • gh-122163: Add notes for JSON serialization errors that allow to identify the source of the error.

  • gh-122129: Improve support of method descriptors and wrappers in the help title.

  • gh-122145: Corrige um problema ao relatar tracebacks correspondentes ao código Python emitindo um corpo AST vazio. Patch de Nikita Sobolev e Bénédikt Tran.

  • gh-121723: Faz logging.config.dictConfig() aceitar qualquer objeto que implemente a API pública Queue. Veja a seção configuração de fila para detalhes. Patch por Bénédikt Tran.

  • gh-82951: Serializa objetos com __qualname__ complexo (como métodos não vinculados e classes aninhadas) por nome não envolve mais serializar objetos pais por valor em protocolos pickle < 4.

  • gh-120754: Pathlib.read_bytes no longer opens the file in Python’s buffered I/O mode. This reduces overheads as the code reads a file in whole leading to a modest speedup.

  • gh-113785: csv agora analisa corretamente campos numéricos (quando usados com csv.QUOTE_NONNUMERIC ou csv.QUOTE_STRINGS) que começam com um caractere de escape.

  • gh-122088: @warnings.deprecated now copies the coroutine status of functions and methods so that inspect.iscoroutinefunction() returns the correct result.

  • gh-122081: Corrige uma falha na função opcional decimal.IEEEContext() disponível por meio do sinalizador de configuração EXTRA_FUNCTIONALITY.

  • gh-73991: Add pathlib.Path.move(), which moves a file or directory tree.

  • gh-121268: Remove workarounds for non-IEEE 754 systems in cmath.

  • gh-119698: Due to the lack of interest for symtable.Class.get_methods(), the method is marked as deprecated and will be removed in Python 3.16. Patch by Bénédikt Tran.

  • gh-121889: Adjusts cmath.acosh(complex('0+nanj')) for recent C standards.

  • gh-121804: Mostra corretamente os locais de erro quando SyntaxError é levantada em um novo repl. Patch por Sergey B Kirpichev.

  • gh-121797: Add alternative Fraction constructor Fraction.from_number().

  • gh-121798: Add alternative Decimal constructor Decimal.from_number().

  • gh-120930: Corrigido um bug introduzido por gh-92081 que adicionava um espaço extra incorreto para palavras codificadas ocorrendo em cabeçalhos encapsulados.

  • gh-57141: O argumento shallow para filecmp.dircmp (novo no Python 3.13) agora é somente-nomeado.

  • gh-121245: Simplifica o tratamento do arquivo de histórico no auxiliar site.register_readline(). A variável CAN_USE_PYREPL agora será inicializada quando importada. Patch por Sergey B Kirpichev.

  • gh-121249: Support the float complex and double complex C types in the struct module if the compiler has C11 complex arithmetic. Patch by Sergey B Kirpichev.

  • gh-121486: math functions isqrt(), log(), log2() and log10() now support integers larger than 2**2**32 on 32-bit platforms.

  • gh-121474: Corrigida a verificação de sanidade ausente para o argumento parties no construtor threading.Barrier. Patch por Clinton Christian (pygeek).

  • gh-121450: Hard-coded breakpoints (breakpoint() and pdb.set_trace()) now reuse the most recent Pdb instance that calls Pdb.set_trace(), instead of creating a new one each time. As a result, all the instance specific data like display and commands are preserved across Hard-coded breakpoints.

  • gh-119169: Slightly speed up os.walk() by simplifying exception handling.

  • gh-121423: Improve import time of socket by lazy importing modules and writing socket.errorTab as a constant.

  • gh-59110: zipimport supports now namespace packages when no directory entry exists.

  • gh-119004: Corrige uma falha em OrderedDict.__eq__ quando operandos são mutados durante a verificação. Patch por Bénédikt Tran.

  • gh-121313: Limit the reading size in the multiprocessing.connection.Connection class to 64 KiB to prevent memory overallocation and unnecessary memory management system calls.

  • gh-121332: Corrige o construtor de nós ast com _attributes personalizados. Anteriormente, passar atributos personalizados levantaria DeprecationWarning. Passar argumentos para o construtor que não estão em _fields ou _attributes continua descontinuado. Patch por Jelle Zijlstra.

  • gh-121245: Corrige um bug no tratamento do histórico de comandos do novo REPL que fazia com que o arquivo de histórico fosse apagado na saída do REPL.

  • gh-121210: Handle AST nodes with missing runtime fields or attributes in ast.compare(). Patch by Bénédikt Tran.

  • gh-121163: Add support for all as an valid action for warnings.simplefilter() and warnings.filterwarnings().

  • gh-121151: Corrige o encapsulamento de texto de uso longo de argumentos dentro de um grupo mutuamente exclusivo em argparse.

  • gh-121141: Add support for copy.replace() to AST nodes. Patch by Bénédikt Tran.

  • gh-87744: Corrige a corrida waitpid ao chamar send_signal() em asyncio. Patch por Kumar Aditya.

  • gh-121027: Adiciona um aviso futuro em functools.partial.__get__(). Em versões futuras do Python, functools.partial será um descritor de método.

  • gh-121027: Make the functools.partial object a method descriptor.

  • gh-117784: CPython now detects whether its linked TLS library supports TLSv1.3 post-handshake authentication and disables that feature if support is lacking.

  • gh-121025: Melhora o __repr__() de functools.partialmethod. Patch por Bénédikt Tran.

  • gh-121018: Fixed issues where argparse.ArgumentParser.parse_args() did not honor exit_on_error=False. Based on patch by Ben Hsing.

  • gh-119614: Corrige truncamento de strings com caracteres nulos incorporados em algumas operações internas em tkinter.

  • gh-120910: Ao ler arquivos instalados de um egg, usa relative_to(walk_up=True) para honrar arquivos instalados fora da raiz da instalação.

  • gh-61103: Support float complex, double complex and long double complex C types in ctypes as c_float_complex, c_double_complex and c_longdouble_complex if the compiler has C11 complex arithmetic. Patch by Sergey B Kirpichev.

  • gh-120888: Atualiza pip wheel empacotado com ensurepip (pip 24.1.1)

  • gh-101830: Acessar a representação de string do objeto tkinter não converte mais o objeto Tcl subjacente em uma string no Windows.

  • gh-120678: Corrigida a regressão no novo REPL que significava que globais de arquivos passados usando o argumento -i não seriam incluídos no namespace global do REPL. Patch por Alex Waygood.

  • gh-120811: Corrige possível vazamento de memória em contextvars.Context.run().

  • gh-120782: Corrigidas referências erradas dos tipos datetime após recarregar o módulo.

  • gh-120713: datetime.datetime.strftime() agora preenche com 0 anos com menos de quatro dígitos para os especificadores de formato %Y e %G no Linux. Patch por Ben Hsing

  • gh-120769: Faz com que uma linha vazia em pdb repita o último comando mesmo quando o comando é de cmdqueue.

  • gh-120780: Show string value of LOAD_SPECIAL oparg in dis output.

  • gh-41431: Add datetime.time.strptime() and datetime.date.strptime(). Contributed by Wannes Boeykens.

  • gh-120743: Soft deprecate os.popen() and os.spawn* functions. They should no longer be used to write new code. The subprocess module is recommended instead. Patch by Victor Stinner.

  • gh-120732: Corrige name passando para o objeto unittest.mock.Mock ao usar unittest.mock.create_autospec().

  • gh-111259: re now handles patterns like "[\s\S]" or "\s|\S" which match any character as effectively as a dot with the DOTALL modifier ("(?s:.)").

  • gh-120683: Corrige um erro em logging.LogRecord, quando a parte inteira do registro de data e hora é arredondada para cima, enquanto o cálculo de milissegundos trunca, fazendo com que o registro de data e hora do log esteja errado em até 999 ms (afetou aproximadamente 1 em 8 milhões de registros de data e hora).

  • gh-118710: ipaddress.IPv4Address and ipaddress.IPv6Address attributes version and max_prefixlen are now available on the class.

  • gh-120633: Move a barra de rolagem e remova os menus destacáveis no turtledemo.

  • gh-120606: Allow users to use EOF to exit commands definition in pdb

  • gh-120284: Allow asyncio.Runner.run() to accept awaitable objects instead of simply coroutines.

  • gh-120541: Melhora o prompt no pager “less” quando help() é chamado com argumento não-string.

  • gh-120495: Corrige o tratamento de exceção incorreto no Tab Nanny. Patch por Wulian233.

  • gh-120388: Improve a warning message when a test method in unittest returns something other than None. Now we show the returned object type and optional asyncio-related tip.

  • gh-120381: Corrige inspect.ismethoddescriptor() para verificar também a falta de __delete__(). Patch por Jan Kaliszewski.

  • gh-90425: O byte do SO em cabeçalhos gzip agora é sempre definido como 255 ao usar gzip.compress().

  • gh-120343: Corrige o relatório de deslocamento de coluna para tokens que vêm depois de f-strings multilinhas no módulo tokenize.

  • gh-119180: As part of implementing PEP 649 and PEP 749, add a new module annotationlib. Add support for unresolved forward references in annotations to dataclasses, typing.TypedDict, and typing.NamedTuple.

  • gh-119600: Corrige unittest.mock.patch() para não ler atributos do alvo quando new_callable estiver definido. Patch por Robert Collins.

  • gh-120289: Fixed the use-after-free issue in cProfile by disallowing disable() and clear() in external timers.

  • gh-82017: Added support for converting any objects that have the as_integer_ratio() method to a Fraction.

  • gh-114053: Corrige bug de caso extremo em que typing.get_type_hints() produziria resultados incorretos se parâmetros de tipo em um escopo de classe fossem substituídos por atribuições em um escopo de classe e a semântica from __future__ import annotations estivesse habilitada. Patch por Alex Waygood.

  • gh-114053: Corrige NameError errôneo ao chamar inspect.get_annotations() com eval_str=True` em uma classe que fazia uso de parâmetros do tipo PEP 695 em um módulo que tinha from __future__ import annotations no topo do arquivo. Patch por Alex Waygood.

  • gh-120268: Proíbe passar None para datetime.date.fromtimestamp() Python puro para obter consistência com a implementação da extensão C.

  • gh-120244: Corrige vazamento de memória em re.sub() quando a string de substituição contém referências anteriores.

  • gh-120254: Added commands argument to pdb.set_trace() which allows users to send debugger commands from the source file.

  • gh-120211: Corrige tkinter.ttk com Tcl/Tk 9.0.

  • gh-71587: Corrige travamento na versão C de datetime.datetime.strptime() quando chamado novamente no interpretador reiniciado.

  • gh-117983: Adia a importação de threading em importlib.util até que o carregamento preguiçoso seja usado.

  • gh-120157: Remove unused constant concurrent.futures._base._FUTURE_STATES in concurrent.futures. Patch by Clinton Christian (pygeek).

  • gh-120161: datetime não trava mais em certas situações complexas de ciclo de referência.

  • gh-119698: Fix symtable.Class.get_methods() and document its behaviour. Patch by Bénédikt Tran.

  • gh-120121: Adiciona concurrent.futures.InvalidStateError ao módulo __all__.

  • gh-119933: Adiciona a enumeração symtable.SymbolTableType para representar as possíveis saídas do método symtable.SymbolTable.get_type. Patch por Bénédikt Tran.

  • gh-120029: Expose symtable.Symbol methods is_free_class(), is_comp_iter() and is_comp_cell(). Patch by Bénédikt Tran.

  • gh-120108: Corrige chamada de copy.deepcopy() em árvores ast que foram modificadas para ter referências a nós pais. Patch por Jelle Zijlstra.

  • gh-120056: Add socket.IP_RECVERR and socket.IP_RECVTTL constants (both available since Linux 2.2). And socket.IP_RECVORIGDSTADDR constant (available since Linux 2.6.29).

  • gh-112672: Suporte para construção de tkinter com Tcl 9.0.

  • gh-120057: Added the os.environ.refresh() method to update os.environ with changes to the environment made by os.putenv(), by os.unsetenv(), or made outside Python in the same process. Patch by Victor Stinner.

  • gh-120029: Expose symtable.Symbol.is_type_parameter() in the symtable module. Patch by Bénédikt Tran.

  • gh-119819: Corrige regressão para permitir configuração de registro com tipos de fila de multiprocessamento.

  • gh-65454: unittest.mock.Mock.attach_mock() não dispara mais uma chamada para um PropertyMock sendo anexado.

  • gh-117142: O módulo ctypes agora pode ser importado em todos os subinterpretadores, incluindo aqueles que têm sua própria GIL.

  • gh-118835: Corrige falha do _pyrepl ao usar prompt personalizado com códigos de escape ANSI.

  • gh-81936: Os métodos help() e showtopic() agora respeitam um argumento output configurado para pydoc.Helper e não usam o pager em tais casos. Patch por Enrico Tröger.

  • gh-117398: O módulo _datetime (implementação C para datetime) agora oferece suporte a importação em múltiplos interpretadores.

  • gh-119824: Print stack entry in pdb when and only when user input is needed.

  • gh-119838: In mixed arithmetic operations with Fraction and complex, the fraction is now converted to float instead of complex.

  • gh-119770: Make termios ioctl() constants positive. Patch by Victor Stinner.

  • gh-89727: Corrige problema com shutil.rmtree() onde uma RecursionError é levantada em árvores de diretório profundas.

  • gh-119577: O DeprecationWarning emitido ao testar o valor verdade de um xml.etree.ElementTree.Element agora descreve o retorno incondicional de True em uma versão futura em vez de gerar uma exceção no Python 3.14.

  • gh-89727: Corrige parcialmente o problema com shutil.rmtree() onde uma RecursionError é levantada em árvores de diretório profundas. Um erro de recursão não é mais levantado quando rmtree.avoids_symlink_attacks é falso.

  • gh-93963: Remove deprecated names from importlib.abc as found in importlib.resources.abc.

  • gh-119118: Corrige regressão de desempenho no módulo tokenize armazenando em cache o atributo de token line e calculando o deslocamento da coluna de forma mais eficiente.

  • gh-89727: Corrige problema com os.fwalk() onde uma RecursionError era levantada em árvores de diretório profundas ajustando a implementação para ser iterativa em vez de recursiva.

  • gh-119594: If one calls pow(fractions.Fraction, x, module) with modulo not None, the error message now says that the types are incompatible rather than saying pow only takes 2 arguments. Patch by Wim Jeantine-Glenn and Mark Dickinson.

  • gh-119588: zipfile.Path.is_symlink agora avalia se o caminho fornecido é um link simbólico.

  • gh-119562: Remove ast.Num, ast.Str, ast.Bytes, ast.NameConstant and ast.Ellipsis. They had all emitted deprecation warnings since Python 3.12. Patch by Alex Waygood.

  • gh-119555: Captura SyntaxError de compile() no método runsource() do InteractiveColoredConsole. Patch por Sergey B Kirpichev.

  • gh-118908: Limita os globais expostos de importações e definições internas na inicialização do novo REPL. Patch por Eugene Triguba e Pablo Galindo.

  • gh-117865: Improve the import time of the ast module by deferring the import of re. Patch by Jelle Zijlstra.

  • gh-119127: Positional arguments of functools.partial() objects now support placeholders via functools.Placeholder.

  • gh-113892: Agora, o método sock_connect de asyncio.ProactorEventLoop levanta um ValueError se o soquete fornecido não estiver no modo não bloqueante, bem como em outras implementações de laço.

  • gh-119506: Corrige o método io.TextIOWrapper.write() que quebra o buffer interno quando o método é chamado novamente durante a descarga do buffer interno.

  • gh-69214: Fix fcntl.ioctl() request parameter: use an unsigned long instead of an unsigned int for the request parameter of fcntl.ioctl() to support requests larger than UINT_MAX. Patch by Victor Stinner.

  • gh-119105: difflib’s DIffer.compare() (and so also ndiff) can no longer be provoked into cubic-time behavior, or into unbounded recursion, and should generally be faster in ordinary cases too. Results may change in some cases, although that should be rare. Correctness of diffs is not affected. Some similar lines far apart may be reported as deleting one and adding the other, where before they were displayed on adjacent output lines with markup showing the intraline differences.

  • gh-119443: O REPL interativo não é mais executado com from __future__ import annotations habilitado. Patch por Jelle Zijlstra.

  • gh-119461: Add socket.VMADDR_CID_LOCAL constant. Patch by Victor Stinner.

  • gh-117398: Os objetos na C-API datetime agora são alocados estaticamente, o que significa melhor segurança de memória, especialmente quando o módulo é recarregado. Isso deve ser transparente para os usuários.

  • gh-118894: asyncio O REPL agora tem os mesmos recursos do PyREPL.

  • gh-118830: Bump pickle default protocol to 5.

  • gh-118911: No PyREPL, a lógica do maybe-accept foi atualizada para que, se o usuário pressionar Enter duas vezes, ele possa encerrar o bloco mesmo se houver um espaço em branco à direita. Além disso, agora, quando o usuário pressiona a seta para cima, o cursor fica na última linha da função. Isso corresponde ao comportamento do IPython. Patch por Aya Elsayed.

  • gh-115225: Raise error on certain technically valid but pathological ISO 8601 strings passed to datetime.time.fromisoformat() that were previously parsed incorrectly.

  • gh-111201: Remove dependência para readline do novo REPL do Python.

  • gh-119189: Ao usar o operador ** ou pow() com Fraction como base e um expoente que não seja racional, um float ou um complexo, a fração não é mais convertida em um float.

  • gh-119174: Corrige DPI alto que causa janelas borradas no turtledemo (exemplos do turtle-graphics) Patch por Wulian233 e Terry Jan Reedy

  • gh-119121: Corrige um NameError acontecendo em asyncio.staggered.staggered_race. Esta função agora está testada.

  • gh-119105: difflib.Differ is much faster for some cases of diffs where many pairs of lines are equally similar.

  • gh-119113: Corrige problema em que pathlib.PurePath.with_suffix() não levantava TypeError quando dado None como sufixo.

  • gh-118643: Corrige um AttributeError no módulo email ao redobrar uma longa lista de endereços. Também corrige mais casos de codificação incorreta do separador de endereços na lista de endereços.

  • gh-73991: Add pathlib.Path.copy(), which copies a file or directory to another.

  • gh-58933: Faz pdb retornar ao quadro do chamador corretamente quando f_trace do quadro do chamador não estiver definido

  • gh-82805: Support single-dot file extensions in pathlib.PurePath.suffix and related attributes and methods. For example, the suffixes of PurePath('foo.bar.') are now ['.bar', '.'] rather than []. This brings file extension splitting in line with os.path.splitext().

  • gh-118924: Remove version and version_info from sqlite3. Patch by Hugo van Kemenade.

  • gh-118928: Disallow using a sequence of parameters with named placeholders in sqlite3 queries. Patch by Erlend E. Aasland.

  • gh-118895: Define atributos em typing.NoDefault agora levanta AttributeError em vez de TypeError.

  • gh-118868: Corrigido o problema em que kwargs não eram mais passados para o manipulador de registro QueueHandler

  • gh-118827: Remove deprecated Quoter class from urllib.parse. It had previously raised a DeprecationWarning since Python 3.11. Patch by Nikita Sobolev.

  • gh-118824: Remove deprecated pty.master_open() and pty.slave_open(). Use pty.openpty() instead. Patch by Nikita Sobolev.

  • gh-118851: Argumentos ctx para os construtores de classes de nó ast agora são padronizados para ast.Load(). Patch por Jelle Zijlstra.

  • gh-101588: Remove copy, deepcopy, and pickle from itertools. These had previously raised a DeprecationWarning since Python 3.12.

  • gh-118805: Remove type, choices, and metavar parameters of argparse.BooleanOptionalAction. They were deprecated since Python 3.12.

  • gh-118803: typing.ByteString and collections.abc.ByteString are removed. They had previously raised a DeprecationWarning since Python 3.12.

  • gh-118798: The isdst parameter has been removed from email.utils.localtime(). Patch by Hugo van Kemenade.

  • gh-118760: Restaura o valor padrão de tkiter.wantobjects para 1.

  • gh-118760: Corrige erros ao chamar ligações Tkinter no Windows.

  • gh-74033: Drop support for passing keyword arguments to pathlib.Path.

  • gh-101357: Suppress all OSError exceptions from pathlib.Path.exists() and is_*() methods, rather than a selection of more common errors. The new behaviour is consistent with os.path.exists(), os.path.isdir(), etc. Use pathlib.Path.stat() to retrieve the file status without suppressing exceptions.

  • gh-78707: Drop support for passing additional positional arguments to pathlib.PurePath.relative_to() and is_relative_to().

  • gh-118507: Corrige os.path.isfile() no Windows para pipes. Acelera os.path.isjunction() e os.path.lexists() no Windows com uma implementação nativa.

  • gh-118772: Permite que instâncias typing.TypeVar sem um padrão sigam instâncias sem um padrão em alguns casos. Patch por Jelle Zijlstra.

  • gh-118714: Permite restart na depuração post-mortem de pdb. Removida a mensagem de reinicialização quando o usuário sai do pdb do modo post-mortem.

  • gh-118673: Removed executable bits and shebang from stdlib modules.

  • gh-110863: os.path.realpath() agora suprime qualquer OSError de os.readlink() quando o modo strict está desabilitado (o padrão).

  • gh-118263: Acelera os.path.splitroot() e os.path.normpath() com uma chamada C direta.

  • gh-110190: Fix ctypes structs with array on SPARC by setting MAX_STRUCT_SIZE to 32 in stgdict. Patch by Jakub Kulik

  • gh-118033: Corrige dataclasses.dataclass() não criando um slot __weakref__ ao subclassificar typing.Generic.

  • gh-117766: Sempre usa str() para exibir choices em argparse.

  • gh-106531: Em importlib.resources, sincronizar com importlib_resources 6.3.2, incluindo: MultiplexedPath agora espera caminhos Traversable, descontinuando argumentos de string para MultiplexedPath; Suporte habilitado para recursos em pacotes de espaço de nomes em arquivos zip; Corrigido NotADirectoryError ao chamar arquivos em um subdiretório de um pacote de espaço de nomes.

  • gh-115937: Removed extra preprocessing for the __signature__ attribute: the code just check if it’s a inspect.Signature instance. Patch by Sergey B Kirpichev.

  • gh-115808: Add operator.is_none() and operator.is_not_none() functions.

  • gh-114264: Improve performance of copy.deepcopy() by adding a fast path for atomic types.

  • gh-113878: Add doc parameter to dataclasses.field(), so it can be stored and shown as a documentation / metadata. If @dataclass(slots=True) is used, then the supplied string is available in the __slots__ dict. Otherwise, the supplied string is only available in the corresponding dataclasses.Field object.

    In order to support this feature we are changing the __slots__ format in dataclasses from tuple to dict when documentation / metadata is present.

  • gh-113978: Ignora avisos sobre conclusão de texto dentro do REPL.

  • gh-113008: Correct argparse usage output for required, mutually exclusive groups containing a positional argument

  • gh-108172: webbrowser honra o navegador preferido do sistema no Linux quando a entrada desktop de nome contém o texto de um nome de navegador conhecido.

  • gh-109109: Agora você pode obter as cadeias de certificados TLS brutas de conexões TLS por meio dos métodos ssl.SSLSocket.get_verified_chain() e ssl.SSLSocket.get_unverified_chain().

    Contribuição de Mateusz Nowak.

  • gh-105623: Corrige degradação de desempenho em logging.handlers.RotatingFileHandler. Patch por Craig Robson.

  • gh-102450: Add missing ISO-8601 24:00 alternative to midnight of next day to datetime.datetime.fromisoformat() and datetime.time.fromisoformat(). Patch by Izan “TizzySaurus” Robinson (tizzysaurus@gmail.com)

  • gh-103956: Corrige a falta de caracteres de nova linha na saída do módulo trace quando o rastreamento de linha está habilitado, mas a linha de código-fonte para o quadro atual não está disponível.

  • gh-92081: Corrige espaços ausentes em cabeçalhos de e-mail quando os espaços são misturados com caracteres codificados de 8 bits.

  • gh-103194: Prepara o Tkinter para alterações na API C no Tcl 8.7/9.0 para evitar que _tkinter.Tcl_Obj seja retornado inesperadamente em vez de bool, str, bytearray ou int.

  • gh-87106: Corrigida a manipulação em inspect.Signature.bind() de argumentos nomeados com o mesmo nome que argumentos somente-posicionais quando um argumento nomeado variádico (por exemplo, **kwargs) estiver presente.

  • gh-103134: Add additional methods to proxy objects in the multiprocessing module:

    • clear() e copy() para proxies de list

    • fromkeys(), reversed(d), d | {}, {} | d, d |= {'b': 2} para proxies de dict

  • bpo-45767: Corrige conversão de inteiros em os.major(), os.minor() e os.makedev(). Suporte a números de dispositivos maiores que 2**63-1. Suporte a número de dispositivos inexistente (NODEV).

  • bpo-44864: Não traduz strings fornecidas pelo usuário em argparse.ArgumentParser.

  • bpo-41843: Solaris now uses os.sendfile() fast-copy syscall for more efficient shutil file copy related functions.

  • bpo-15987: Implemented ast.compare() for comparing two ASTs. Patch by Batuhan Taskaya with some help from Jeremy Hylton.

  • gh-67693: Corrige urllib.parse.urlunparse() e urllib.parse.urlunsplit() para URIs com caminho começando com várias barras e sem autoridade. Baseado no patch de Ashwin Ramaswami.

  • bpo-14074: Corrige o processamento de metavariável de argparse para permitir que argumentos posicionais tenham uma metavar de tupla.

IDLE

  • gh-122392: Aumenta o espaçamento vertical atualmente inadequado para os navegadores IDLE (caminho, módulo e pilha) em monitores de alta resolução.

  • gh-112938: Corrige travamento ininterrupto quando o console obtém saída rápida e contínua.

  • gh-122482: Alterado o Sobre do IDLE para direcionar os usuários para discuss.python.org em vez do e-mail e lista de discussão idle-dev, agora não utilizados.

  • gh-78889: Para o congelamentos do Shell bloqueando o acesso do usuário a atributos sys.stdout.shell que não são métodos, que são todos privados.

  • gh-120083: Adiciona a cor preta explícita como primeiro plano de dicas flutuantes (hovertips) do IDLE, necessário para macOS recentes. Corrige o Sonoma mostrando branco ilegível em amarelo claro. Patch por John Riggles.

  • gh-120104: Corrige preenchimento em janelas de diálogo de configuração e pesquisa no IDLE.

Documentação

  • gh-124872: Adicionadas as definições para contexto, contexto atual e protocolo de gerenciamento de contexto, atualizadas definições relacionadas para serem consistentes e expandida a documentação para contextvars.Context.

  • gh-125018: A documentação importlib.metadata agora inclui alvos de referência cruzada semântica para as APIs documentadas significativas. Isso significa que referências intersphinx como importlib.metadata.version() agora funcionarão conforme o esperado.

  • gh-124720: Atualiza a seção “Usando Python em um Mac” do documento “Configuração e uso do Python” e incluir informações sobre a instalação do suporte a threads livres.

  • gh-124457: Remove coverity scan from the CPython repo. It has not been used since 2020 and is currently unmaintained.

  • gh-116622: Adiciona um guia de plataforma Android e sinaliza módulos não disponíveis no Android.

  • gh-123976: Refresh docs around custom providers.

  • gh-70870: Esclarecido o uso duplo do termo “variável livre” (tanto o significado formal de qualquer referência a nomes definidos fora do escopo local, quanto o significado pragmático mais restrito de variáveis não locais nomeadas em co_freevars).

  • gh-121277: Os escritores da documentação do CPython agora podem usar next como a versão para as diretivas versionchanged, versionadded, deprecated.

  • gh-117765: Improved documentation for unittest.mock.patch.dict()

  • gh-121749: Corrige documentação para PyModule_AddObjectRef().

  • gh-120012: Esclarece os comportamentos de multiprocessing.Queue.empty() e multiprocessing.SimpleQueue.empty() em filas fechadas. Patch por Bénédikt Tran.

  • gh-119574: Added some missing environment variables to the output of --help-env.

  • bpo-34008: A documentação Py_Main() foi movida da seção “API de nível muito alto” para a seção “Inicialização e finalização”.

    Também explicita que esperamos que Py_Main seja chamado tipicamente em vez de Py_Initialize em vez de depois dele (já que Py_Main faz sua própria chamada para Py_Initialize). Documente que chamar ambos é suportado, mas depende da versão de quais configurações serão aplicadas corretamente.

Núcleo e embutidos

  • gh-124375: Corrige uma falha na construção com threads livres quando o GC é executado simultaneamente com uma nova thread iniciando.

  • gh-125221: Corrige possível condição de corrida ao chamar __reduce_ex__() pela primeira vez na construção com threads livres.

  • gh-125174: Make the handling of reference counts of immortal objects more robust. Immortal objects with reference counts that deviate from their original reference count by up to a billion (half a billion on 32 bit builds) are still counted as immortal.

  • gh-125039: Make this_instr and prev_instr const in cases generator.

Biblioteca

Núcleo e embutidos

  • gh-124871: Corrige bug do compilador (em algumas versões do 3.13) onde uma asserção falha durante a análise de acessibilidade.

  • gh-123378: Corrige uma falha no método __str__() de objetos UnicodeError quando os valores UnicodeError.start e UnicodeError.end são inválidos ou estão fora do intervalo. Patch por Bénédikt Tran.

  • gh-118093: Improve the experimental JIT compiler’s ability to stay “on trace” when encountering highly-biased branches.

  • gh-124642: Corrigido problema de escalabilidade em construções com threads livres para leituras sem travas de dicionários em cenários de multithread

  • gh-116510: Corrige uma falha causada por strings internas imortais sendo compartilhadas entre subinterpretadores que usam inicialização básica de fase única. Nesse caso, a string pode ser usada por um interpretador que sobrevive ao interpretador que a criou e a internou. Para interpretadores que compartilham o estado obmalloc, compartilhe também o dict interno com o interpretador principal.

  • gh-116510: Corrige um bug que pode causar uma falha quando subinterpretadores usam módulos “básicos” de extensão de fase única. Objetos compartilhados podem se referir a nós PyGC_Head que foram liberados como parte da limpeza do interpretador.

  • gh-119180: The __main__ module no longer always contains an __annotations__ dictionary in its global namespace.

  • gh-124547: Ao desalocar um objeto com valores inline cujo __dict__ ainda está ativo: se a alocação de memória para os valores inline falhar, limpe o dicionário. Evita uma falha do interpretador.

  • gh-124513: Corrige uma falha no construtor FrameLocalsProxy: verifica o número de argumentos. Patch por Victor Stinner.

  • gh-124442: Corrige não determinismo na compilação classificando o valor de __static_attributes__. Patch por kp2pml30.

  • gh-124285: Fix bug where bool(a) can be invoked more than once during the evaluation of a compound boolean expression.

  • gh-123856: Corrige falha do PyREPL quando uma interrupção de teclado é acionada após usar uma pesquisa de histórico

  • gh-65961: Deprecate the setting and using __package__ and __cached__.

  • gh-119726: The JIT now generates more efficient code for calls to C functions resulting in up to 0.8% memory savings and 1.5% speed improvement on AArch64. Patch by Diego Russo.

  • gh-122878: Usa o binário pager, se disponível (por exemplo, no Debian e derivados), para exibir REPL help().

  • gh-124188: Fix reading and decoding a line from the source file with non-UTF-8 encoding for syntax errors raised in the compiler.

  • gh-124027: Suporte às chaves <page up>, <page down> e <delete> no Python REPL quando $TERM estiver definido como vt100.

  • gh-124022: Fix bug where docstring is removed from classes in interactive mode.

  • gh-123958: docstrings are now removed from the optimized AST in optimization level 2.

  • gh-123923: The f_executable field in the internal _PyInterpreterFrame struct now uses a tagged pointer. Profilers and debuggers that uses this field should clear the least significant bit to recover the PyObject* pointer.

  • gh-77894: Corrige possível travamento no coletor de lixo quando ele tenta quebrar um laço de referência contendo um objeto memoryview. Agora, um objeto memoryview só pode ser limpo se não houver buffers que o referenciem.

  • gh-120221: o REPL do asyncio agora está reconhecendo corretamente KeyboardInterrupts. A exibição de exceções levantadas em threads secundárias foi corrigida.

  • gh-119310: Permite que o novo console interativo leia arquivos de histórico escritos com a biblioteca editline que usam entradas com escape unicode. Patch por aorcajo e Łukasz Langa.

  • gh-123572: Corrige mapeamentos de teclas para várias teclas F no Windows para o novo REPL. Patch por devdanzin

Biblioteca

  • gh-123614: Add turtle.save() to easily save Turtle drawings as PostScript files. Patch by Marie Roald and Yngve Mardal Moe.

Núcleo e embutidos

  • gh-123339: Define o atributo __module__ para uma classe agora remove o item __firstlineno__ do dict do tipo, então eles não serão mais inconsistentes.

  • gh-119034: Altera as teclas <page up> e <page down> do REPL do Python para pesquisa de histórico para frente/para trás. Patch por Victor Stinner.

  • gh-123562: Improve SyntaxError message for using case ... as ... with not a name.

  • gh-123545: Corrige um decref duplo em casos raros em construções JIT experimentais.

  • gh-123484: Corrige _Py_DebugOffsets para objetos longos para serem relativos ao início do objeto em vez do início de um subobjeto.

  • gh-123446: Fix empty function name in TypeError when builtin magic methods are used without the required args.

  • gh-123440: Improve SyntaxError message for using except as with not a name.

  • gh-116017: Improved JIT memory consumption by periodically freeing memory used by infrequently-executed code. This change is especially likely to improve the memory footprint of long-running programs.

  • gh-123344: Adiciona otimizações AST para padrões de parâmetros de tipo.

  • gh-123321: Impede que a condição de corrida Parser/myreadline apresente falhas de segmentação no uso multithread. Patch por Bar Harel e Amit Wienner.

  • gh-123177: Corrige um bug que causava o aparecimento de prompts perdidos no meio de linhas quebradas no novo REPL.

  • gh-122982: Estende o período de descontinuação para inversão de bool (~) em dois anos.

  • gh-123271: Make concurrent iterations over the same zip() iterator safe under free-threading.

  • gh-123275: Suporte a -X gil=1 e a PYTHON_GIL=1 em construções sem threads livres.

  • gh-123177: Desativa quebra de linha no Apple Terminal por meio de um código de escape ANSI. Patch por Pablo Galindo

  • gh-123229: Corrige o aviso valgrind inicializando os buffers f-string para 0 no tokenizador. Patch por Pablo Galindo

  • gh-122298: Restore printout of GC stats when gc.set_debug(gc.DEBUG_STATS) is called. This feature was accidentally removed when implementing incremental GC.

  • gh-121804: Mostra corretamente os locais de erro quando uma SyntaxError é levanta no REPL básico. Patch por Sergey B Kirpichev.

  • gh-115776: Enables inline values (Python’s equivalent of hidden classes) on any class who’s instances are of a fixed size.

  • gh-123142: Corrige o local de origem muito amplo em tracebacks de exceção provenientes de iteráveis quebrados em compreensões.

  • gh-123048: Corrige um bug em que o código de correspondência de padrões poderia emitir um JUMP_FORWARD sem local de origem.

  • gh-118093: Break up CALL_ALLOC_AND_ENTER_INIT into micro-ops and relax requirement for exact args, in order to increase the amount of code supported by tier 2.

  • gh-123123: Corrige a exibição de exceções SyntaxError cobrindo várias linhas. Patch por Pablo Galindo

  • gh-123083: Corrige um possível uso após liberação em STORE_ATTR_WITH_HINT.

  • gh-123022: Corrige falha em construção com threads livres ao chamar Py_Initialize() de uma thread não principal.

  • gh-118093: Add three specializations for CALL_KW:

    • CALL_KW_PY for calls to Python functions

    • CALL_KW_BOUND_METHOD for calls to bound methods

    • CALL_KW_NON_PY for all other calls

  • gh-122821: Make sure that branches in while statements have consistent offsets for sys.monitoring. while statements are now compiled with a simple jump at the end of the body, instead of duplicating the test.

  • gh-122907: A construção com HAVE_DYNAMIC_LOADING agora funciona tão bem quanto no 3.12. As deficiências existentes serão abordadas separadamente. (Consulte https://github.com/python/cpython/issues/122950.)

  • gh-122888: Corrige falha em certas chamadas para str() com argumentos posicionais do tipo errado. Patch por Jelle Zijlstra.

  • gh-118093: Improve the experimental JIT’s handling of polymorphic code.

  • gh-122697: Fixed memory leaks at interpreter shutdown in the free-threaded build, and also reporting of leaked memory blocks via -X showrefcount.

  • gh-116622: Corrige mensagens stdout e stderr do Android sendo truncadas ou perdidas.

  • gh-122527: Corrige uma falha que ocorria quando um PyStructSequence era desalocado após o dicionário do seu tipo ser limpo pelo GC. O tp_basicsize do tipo agora considera campos não sequenciais que não estão incluídos no Py_SIZE da sequência.

  • gh-122445: Adiciona somente campos que são modificados via self.* para __static_attributes__.

  • gh-122417: In the free-threaded build, the reference counts for heap type objects are now partially stored in a distributed manner in per-thread arrays. This reduces contention on the heap type’s reference count fields when creating or destroying instances of the same type from multiple threads concurrently.

  • gh-116090: Corrige um problema em construções JIT que impediam alguns loops for de disparar corretamente eventos de monitoramento RAISE.

  • gh-122300: Preserva nós AST para f-string com especificadores de formato de elemento único. Patch por Pablo Galindo

  • gh-120906: frame.f_locals agora oferece suporte a objetos hash arbitrários como chaves.

  • gh-122239: When a list, tuple or dict with too many elements is unpacked, show the actual length in the error message.

  • gh-122245: Detection of writes to __debug__ is moved from the compiler’s codegen stage to the symtable. This means that these errors are now detected even in code that is optimized away before codegen (such as assertions with the -O command line option).

  • gh-122234: Specializations for sums with float and complex inputs in sum() now always use compensated summation. Also, for integer items in above specializations: PyLong_AsDouble() is used, instead of PyLong_AsLongAndOverflow(). Patch by Sergey B Kirpichev.

  • gh-122208: Os monitoradores de dicionário agora só entregam o evento PyDict_EVENT_ADDED quando a inserção está em um estado conhecido como bom para ser bem-sucedida.

  • gh-122160: Remove the BUILD_CONST_KEY_MAP opcode. Use BUILD_MAP instead.

  • gh-122029: Emite eventos c_call em sys.setprofile() quando um PyMethodObject apontando para um PyCFunction é chamado.

  • gh-122026: Corrige um bug que fazia com que o tokenizador não identificasse corretamente parênteses incompatíveis dentro de f-strings em algumas situações. Patch por Pablo Galindo

  • gh-99108: Python’s hashlib now unconditionally uses the vendored HACL* library for Blake2. Python no longer accepts libb2 as an optional dependency for Blake2.

    We refreshed HACL* to the latest version, and now vendor HACL*’s 128-bit and 256-bit wide vector implementations for Blake2, which are used on x86/x64 toolchains when the required CPU features are available at runtime.

    HACL*’s 128-bit wide vector implementation of Blake2 can also run on ARM NEON and Power8, but lacking evidence of a performance gain, these are not enabled (yet).

Biblioteca

Núcleo e embutidos

  • gh-121860: Corrige travamento ao rematerializar um dicionário gerenciado após ele ter sido excluído.

  • gh-121795: Improve performance of set membership testing, set.remove() and set.discard() when the argument is a set.

  • gh-121814: Corrigido o SegFault quando PyEval_SetTrace() é usado sem nenhum quadro Python na pilha.

  • gh-121295: Corrigido o console PyREPL entrando em um estado bloqueado após interromper uma colagem longa

  • gh-121794: Corrigido o bug no Python de threads livres onde um objeto ressuscitado poderia levar a uma falha de asserção de contagem de referência negativa.

  • gh-121657: Melhorada a mensagem de SyntaxError se o usuário tentar usar yield from fora de uma função.

  • gh-121609: Corrigido o ato de colar caracteres contendo unicode character joiners no novo REPL. Patch por Marta Gomez Macias

  • gh-121297: Previously, incorrect usage of await or asynchronous comprehensions in code removed by the -O option was not flagged by the Python compiler. Now, such code raises SyntaxError. Patch by Jelle Zijlstra.

  • gh-117482: Invólucros de slot inesperados não são mais criados para tipos estáticos embutidos em subinterpretadores.

  • gh-121562: Optimized performance of hex_from_char by replacing switch-case with a lookup table

  • gh-121499: Corrige um bug que afetava como o histórico multilinha estava sendo renderizado no novo REPL após interagir com o novo cache de tela. Patch por Pablo Galindo

  • gh-121497: Corrige um bug que impedia o REPL de respeitar corretamente o histórico quando um gancho de entrada era definido. Patch por Pablo Galindo

  • gh-121012: A execução do nível 2 agora garante que os iteradores de lista permaneçam esgotados, uma vez que se esgotem.

  • gh-121439: Permite que tuplas de comprimento 20 na lista de liberação sejam reutilizadas.

  • gh-121288: ValueError messages for list.index(), range.index(), deque.index(), deque.remove() and ShareableList.index() no longer contain the repr of the searched value (which can be arbitrary large) and are consistent with error messages for other index() and remove() methods.

  • gh-121368: Corrige a condição de corrida em _PyType_Lookup na construção com threads livres devido a uma cerca de memória ausente. Isso pode levar _PyType_Lookup a retornar resultados incorretos no arm64.

  • gh-121149: Added specialization for summation of complexes, this also improves accuracy of builtin sum() for such inputs. Patch by Sergey B Kirpichev.

  • gh-121130: Corrige f-strings com expressões de depuração em especificadores de formato. Patch por Pablo Galindo

Biblioteca

  • gh-121381: Remove subprocess._USE_VFORK escape hatch code and documentation. It was added just in case, and doesn’t have any known cases that require it.

Núcleo e embutidos

  • gh-119726: Optimize code layout for calls to C functions from the JIT on AArch64. Patch by Diego Russo.

  • gh-121115: PyLong_AsNativeBytes() não usa mais métodos __index__() por padrão. O sinalizador Py_ASNATIVEBYTES_ALLOW_INDEX foi adicionado para permitir isso.

  • gh-120838: Py_Finalize() e Py_FinalizeEx() agora sempre são executados com o interpretador principal ativo.

  • gh-113433: Subinterpretadores agora são limpos automaticamente durante a finalização do tempo de execução.

  • gh-119726: Improve the speed and memory use of C function calls from JIT code on AArch64. Patch by Diego Russo

  • gh-116017: Simplify the warmup mechanism used for “side exits” in JIT code, resulting in slightly better performance and slightly lower memory usage for most platforms.

  • gh-98442: Corrige localizações de origem muito amplas das instruções de limpeza de uma declaração with.

  • gh-120754: Reduce the number of system calls invoked when reading a whole file (ex. open('a.txt').read()). For a sample program that reads the contents of the 400+ .rst files in the cpython repository Doc folder, there is an over 10% reduction in system call count.

  • gh-119462: Make sure that invariants of type versioning are maintained: * Superclasses always have their version number assigned before subclasses * The version tag is always zero if the tag is not valid. * The version tag is always non-if the tag is valid.

  • gh-120437: Corrige problemas de otimização _CHECK_STACK_SPACE introduzidos em gh-118322.

  • gh-120722: Define corretamente a posição do bytecode em instruções de retorno dentro de lambdas. Patch por Jelle Zijlstra.

  • gh-120367: Corrige bug onde o compilador cria um salto redundante durante a substituição de pseudo-op. Só pode acontecer com um AST sintético que tenha uma tentativa na mesma linha que a instrução após o manipulador de exceção.

  • gh-120507: Remove the BEFORE_WITH and BEFORE_ASYNC_WITH instructions. Add the new LOAD_SPECIAL instruction. Generate code for with and async with statements using the new instruction.

  • gh-113993: Strings internalizadas com sys.intern() são novamente coletadas como lixo quando não são mais usadas, conforme a documentação. Strings internadas com a função C PyUnicode_InternInPlace() ainda são imortais. Os internos do mecanismo de internação de strings foram alterados. Isso pode afetar o desempenho e as identidades dos objetos str.

Biblioteca

  • gh-120485: Add an override of allow_reuse_port on classes subclassing socketserver.TCPServer where allow_reuse_address is also overridden.

Núcleo e embutidos

  • gh-120384: Fix an array out of bounds crash in list_ass_subscript, which could be invoked via some specifically tailored input: including concurrent modification of a list object, where one thread assigns a slice and another clears it.

  • gh-120367: Corrige falha no compilador em código com NOPs e JUMPs redundantes que aparecem depois que os manipuladores de exceção são movidos para o final do código.

Biblioteca

Núcleo e embutidos

  • gh-120397: Improve the throughput by up to two times for the str.count(), bytes.count() and bytearray.count() methods for counting single characters.

  • gh-120221: Entrega sinais reais em Ctrl-C e Ctrl-Z no novo REPL. Patch por Pablo Galindo

  • gh-120346: Respect PYTHON_BASIC_REPL when running in interactive inspect mode (python -i). Patch by Pablo Galindo

  • gh-93691: Corrige os locais de origem das instruções geradas para o iterador de uma instrução for.

  • gh-120198: Corrige uma falha quando vários threads leem e escrevem na mesma __class__ de um objeto simultaneamente.

  • gh-120298: Fix use-after free in list_richcompare_impl which can be invoked via some specifically tailored evil input.

  • gh-119666: Corrige uma falha do compilador no caso em que duas compreensões no escopo da classe referenciam __class__.

  • gh-119726: JIT: Re-use trampolines on AArch64 when creating stencils. Patch by Diego Russo

  • gh-120225: Corrige a falha no compilador em bloco vazio no final do manipulador de exceção.

  • gh-93691: Corrige localizações de origem de instruções geradas para declarações with.

  • gh-120097: FrameLocalsProxy agora é uma subclasse de collections.abc.Mapping e pode ser correspondido como um mapeamento em instruções match

  • gh-120080: Direct call to the int.__round__() now accepts None as a valid argument.

  • gh-119933: Melhora as mensagens SyntaxError para expressões inválidas em um limite de parâmetros de tipo, uma tupla de restrição de parâmetro de tipo ou um parâmetro de tipo padrão. Patch por Bénédikt Tran.

  • gh-119724: Revertidas as melhorias para mensagens de erro para instruções elif/else que não correspondem a nenhuma instrução válida, o que torna difícil localizar os erros de sintaxe dentro desses blocos elif/else.

  • gh-119879: String search is now slightly faster for certain cases. It now utilizes last character gap (good suffix rule) for two-way periodic needles.

  • gh-119842: Honra PyOS_InputHook() no novo REPL. Patch por Pablo Galindo

  • gh-119180: classmethod() and staticmethod() now wrap the __annotations__ and __annotate__ attributes of their underlying callable lazily. See PEP 649. Patch by Jelle Zijlstra.

  • gh-119821: Corrige a execução de escopos de anotação dentro de classes quando globals estiver definido como um não-dict. Patch por Jelle Zijlstra.

  • gh-118934: Faz PyEval_GetLocals retornar referência emprestada

  • gh-119740: Remove the previously-deprecated delegation of int() to __trunc__().

  • gh-119689: Generate stack effect metadata for pseudo instructions from bytecodes.c.

  • gh-109218: complex() accepts now a string only as a positional argument. Passing a complex number as the “real” or “imag” argument is deprecated; it should only be passed as a single positional argument.

  • gh-119548: Adiciona um comando clear ao REPL. Patch por Pablo Galindo

  • gh-111999: Corrige a assinatura de str.format_map().

  • gh-119560: Uma asserção inválida no beta 1 foi removida. A asserção falharia se PyState_FindModule() fosse usada na função init de um módulo de extensão antes que o módulo def tivesse sido inicializado.

  • gh-119369: Corrige um impasse (deadlock) durante a exclusão de thread em construção com threads livres, que poderia ocorrer quando a GIL foi habilitada em tempo de execução.

  • gh-119525: Corrige o impasse envolvendo o cache _PyType_Lookup() na construção com threads livres quando a GIL é habilitada dinamicamente em tempo de execução.

  • gh-119258: Eliminate type version guards in the tier two interpreter.

    Note that setting the tp_version_tag manually (which has never been supported) may result in crashes.

  • gh-119311: Corrige bug onde nomes são inesperadamente cortados nas bases de classes genéricas.

  • gh-119395: Corrige bug onde nomes aparecendo após uma classe genérica são cortados como se estivessem na classe genérica.

  • gh-119372: Correct invalid corner cases in complex division (resulted in (nan+nanj) output), e.g. 1/complex('(inf+infj)'). Patch by Sergey B Kirpichev.

  • gh-119180: Evaluation of annotations is now deferred. See PEP 649 for details.

  • gh-119180: Replace LOAD_ASSERTION_ERROR opcode with LOAD_COMMON_CONSTANT and add support for NotImplementedError.

  • gh-119213: Módulos não embutidos construídos com a clínica de argumentos estavam travando se usados em um subinterpretador antes do interpretador principal. Os objetos que estavam causando o problema por vazamento entre os interpretadores descuidadamente foram corrigidos.

  • gh-119011: Corrige type.__type_params__ para retornar uma tupla vazia em vez de um descritor.

  • gh-118692: Evita criar instâncias StopIteration desnecessárias para monitoramento.

  • gh-119180: Add an __annotate__ attribute to functions, classes, and modules as part of PEP 649. Patch by Jelle Zijlstra.

  • gh-119049: Corrige a exibição da linha de origem para avisos criados pela API C se o módulo warnings ainda não tiver sido importado.

  • gh-119057: Improve ZeroDivisionError error message. Now, all error messages are harmonized: all /, //, and % operations just use “division by zero” message. And 0 ** -1 operation uses “zero to a negative power”.

  • gh-118844: Corrige falhas de construção ao configurar com --disable-gil e --enable-experimental-jit.

  • gh-118921: Adiciona o método copy() para FrameLocalsProxy que retorna um dict para variáveis locais.

  • gh-117657: Corrige corridas de dados no campo que armazena um ponteiro para a thread principal do interpretador que ocorrem em construções com threads livres.

  • gh-118750: If the C version of the decimal module is available, int(str) now uses it to supply an asymptotically much faster conversion. However, this only applies if the string contains over about 2 million digits.

  • gh-118767: Using NotImplemented in a boolean context now raises TypeError. Contributed by Jelle Zijlstra.

  • gh-118561: Fix race condition in free-threaded build where list.extend() could expose uninitialised memory to concurrent readers.

  • gh-117139: Convert the Python evaluation stack to use internal stack references. The purpose is to support tagged pointers. In PEP 703, this will allow for its form of deferred reference counting. For both the default and free-threaded builds, this sets up the infrastructure for unboxed integers in the future.

Biblioteca

Núcleo e embutidos

  • gh-117558: Improve error messages when a string, bytes or bytearray object of length 1 is expected.

  • gh-117195: Evita falha de asserção para construções de depuração ao chamar object.__sizeof__(1)

  • gh-116022: Improve the __repr__() output of AST nodes.

  • gh-114091: Changed the error message for awaiting something that can’t be awaited from “object <type> can’t be used in an await expression” to “’<type>’ object can’t be awaited”.

  • gh-113190: Py_Finalize() now deletes all interned strings.

  • gh-84978: Add class methods float.from_number() and complex.from_number().

  • gh-95144: Improve the error message from a in b when b is not a container to mention the term “container”.

  • bpo-24766: Corrige manipulação do argumento doc para subclasses de property.

API C

Construção

  • gh-125269: Corrige a detecção de se -latomic é necessário ao fazer compilação cruzada do CPython usando o script configure.

  • gh-123990: Remove WITH_FREELISTS macro and --without-freelists build configuration

  • gh-124102: Update internal documentation under PCbuild, so it now correctly states that Windows requires VS2017 or later and Python 3.10 or later

  • gh-124043: Construir usando --with-trace-refs é (temporariamente) proibido quando a GIL está desabilitado.

  • gh-123418: Atualizada construção do Android para usar OpenSSL 3.0.15.

  • gh-123297: Propaga o valor de LDFLAGS para LDCXXSHARED em sysconfig. Patch por Pablo Galindo

  • gh-121634: Permite especificar o triplo de compilação de destino para WASI.

  • gh-122578: Usa WASI SDK 24 para testes.

  • gh-116622: Renomeia variável de construção MODULE_LDFLAGS de volta para LIBPYTHON, como é usada por sistemas de construção de pacotes (por exemplo, Meson).

  • gh-118943: Corrige um problema em que o JIT experimental poderia ser construído várias vezes pelo alvo make regen-all, levando a possíveis condições de corrida em construções fortemente paralelizadas.

  • gh-121996: Introduce ./configure –disable-safety and –enable-slower-safety options. Patch by Donghee Na.

  • gh-120522: Adicionada uma opção --with-app-store-compliance para corrigir problemas conhecidos com processos de revisão da App Store do macOS/iOS.

  • gh-120371: Suporta WASI SDK 22 ignorando explicitamente funções que são apenas stubs em wasi-libc.

  • gh-121731: Corrige erro de construção mimalloc no GNU/Hurd

  • gh-121487: Corrige aviso de descontinuação para ATOMIC_VAR_INIT em mimalloc.

  • gh-121467: Corrige um bug do Makefile que impedia a instalação de arquivos de cabeçalho mimalloc.

  • gh-121103: Em sistemas POSIX, excluindo instalações do framework macOS, o diretório lib para a construção com threads livres agora inclui um sufixo “t” para evitar conflitos com uma instalação de construção padrão co-localizada.

  • gh-120831: A versão mínima padrão do iOS foi aumentada para 13.0.

  • gh-121082: Fix build failure when the developer use --enable-pystats arguments in configuration command after #118450.

  • gh-120671: Corrige testes de configuração com falha devido a um espaço ausente ao anexar a CFLAGS.

  • gh-120602: Manipula corretamente instalações LLVM com LLVM_VERSION_SUFFIX ao construir com --enable-experimental-jit.

  • gh-120688: On WASI in debug mode, Python is now built with compiler flag -O3 instead of -Og, to support more recursive calls. Patch by Victor Stinner.

  • gh-118943: Corrige uma possível condição de corrida afetando construções paralelas configuradas com --enable-experimental-jit, em que FileNotFoundError poderia ser causado por outro processo que já estava movendo jit_stencils.h.new para jit_stencils.h.

  • gh-120326: No Windows, corrige o erro de construção quando as opções --disable-gil e --experimental-jit são combinadas.

  • gh-120291: Torna o script de shell python-config compatível com shells além do bash.

  • gh-113565: Melhora as verificações de dependência curses e curses.panel em configure.

  • gh-119729: Em sistemas POSIX, os nomes de arquivo pkg-config (.pc) agora incluem os sinalizadores ABI, que podem incluir debug ("d") e free-threaded ("t"). Por exemplo: * python-3.14.pc (padrão, construção não-debug) * python-3.14d.pc (padrão, construção debug) * python-3.14t.pc (construção com threads livres)

  • gh-119400: make_ssl_certs, the script that prepares certificate data for the test suite, now allows specifying expiration dates.

  • gh-115119: Retorna ao libmpdec empacotado se uma versão do sistema não puder ser encontrada.

  • gh-119132: Atualiza sys.version para identificar se a construção é a construção padrão ou a construção com threads livres. Patch por Donghee Na.

  • gh-118836: Corrige um AssertionError ao construir com --enable-experimental-jit e o compilador emite uma seção SHT_NOTE.

  • gh-118943: Corrige uma possível condição de corrida que afeta construções paralelas configuradas com --enable-experimental-jit, nas quais erros de construção podem ser causados por um arquivo de cabeçalho gerado de forma incompleta.

Python 3.13.0 beta 1

Data de lançamento: 2024-05-08

Segurança

  • gh-116741: Atualiza libexpat empacotado para 2.6.2

  • gh-117233: Detecta suporte a BLAKE2, SHA3, Shake e SHA512 truncado na biblioteca libcrypto do OpenSSL no momento da construção. Isso permite que hashlib seja usado com bibliotecas que não suportam todos os algoritmos que o OpenSSL upstream suporta.

Núcleo e embutidos

  • gh-118414: Adiciona opcodes instrumentados à asserção YIELD_VALUE para rastrear casos.

  • gh-117953: Quando um módulo embutido ou de extensão é importado pela primeira vez, enquanto um subinterpretador está ativo, a função init do módulo agora é executada pelo interpretador principal antes que a importação continue no subinterpretador. Consequentemente, os módulos init de fase única agora falham em um subinterpretador isolado sem a função init em execução sob esse interpretador, enquanto antes ele seria executado sob o subinterpretador antes de falhar, potencialmente deixando para trás o estado global e os retornos de chamada e, de outra forma, deixando o módulo em um estado inconsistente.

  • gh-117549: Não usa a sintaxe do inicializador designado em funções inline em cabeçalhos internos. Eles causam problemas para usuários de C++ ou MSVC que ainda não estão usando o padrão C++ mais recente (C++20). Enquanto interno, pycore_backoff.h, é incluído (indiretamente, via pycore_code.h) por algum software de terceiros importante que faz isso para velocidade.

Biblioteca

  • gh-95382: Melhora o desempenho de json.dumps() e json.dump() ao usar o argumento indent. Dependendo dos dados, a codificação usando json.dumps() com indent pode ser de 2 a 3 vezes mais rápida.

Núcleo e embutidos

  • gh-116322: Em construções com --disable-gil, a GIL será habilitada durante o carregamento de módulos de extensão C. Se o módulo indicar que suporta execução sem a GIL, a GIL será desabilitada quando o carregamento for concluído. Caso contrário, a GIL permanecerá habilitada pelo restante da vida útil do interpretador. Esse comportamento não se aplica se a GIL tiver sido explicitamente habilitada ou desabilitada com PYTHON_GIL ou -Xgil.

  • gh-118513: Corrige UnboundLocalError incorreta quando duas compreensões na mesma função referenciam o mesmo nome e, em uma compreensão, o nome é vinculado, enquanto na outra é um global implícito.

  • gh-118518: Permite que o suporte Linux perf funcione sem ponteiros de quadro usando o suporte JIT avançado do perf. O recurso é ativado ao usar a variável de ambiente PYTHON_PERF_JIT_SUPPORT ou ao executar Python com -Xperf_jit. Patch por Pablo Galindo.

  • gh-117514: Adiciona a função sys._is_gil_enabled() que retorna se a GIL está habilitada no momento. Na construção padrão, ela sempre retorna True porque a GIL está sempre habilitada. Na construção com threads livres, ela pode retornar True ou False.

  • gh-118164: Interrompe um laço entre a implementação Python do módulo decimal e o código Python para conversão de inteiro para string. Também otimize a conversão de inteiro para string para valores no intervalo de 9_000 a 135_000 dígitos decimais.

  • gh-118473: Corrige sys.set_asyncgen_hooks() para não ser parcialmente definido ao levantar TypeError.

  • gh-118465: O compilador preenche o novo campo __firstlineno__ em uma classe com o número da linha da primeira linha da definição da classe.

  • gh-118492: Corrige um problema em que o cache de tipos pode expor um atributo acessado anteriormente quando um finalizador é executado.

  • gh-117714: atualiza async_generator.athrow().close() e async_generator.asend().close() para fechar sua seção do gerador assíncrono subjacente

  • gh-111201: O interpretador interativo agora é implementado em Python, o que permite uma série de novos recursos como cores, entrada multilinha, visualização de histórico e modo de colagem. Contribuído por Pablo Galindo, Łukasz Langa e Lysandros Nikolaou com base no código do projeto PyPy.

  • gh-74929: Implementa PEP 667: convertido FrameType.f_locals e PyFrame_GetLocals() para retornar um objeto proxy de gravação quando o quadro se refere a uma função ou compreensão.

  • gh-116767: Corrige travamento no compilador em ‘async with’ que tem muitos gerenciadores de contexto.

  • gh-118335: Altera como usar o interpretador de nível 2. Em vez de executar Python com -X uops ou definir a variável de ambiente PYTHON_UOPS=1, essa escolha agora é feita em tempo de construção configurando com --enable-experimental-jit=interpreter.

    Cuidado! Isso altera a variável de ambiente para habilitar ou desabilitar micro-ops para PYTHON_JIT. O antigo PYTHON_UOPS não é mais usado.

  • gh-118306: Atualiza a compilação JIT para usar LLVM 18

  • gh-118160: Escopos de anotação dentro de classes agora podem conter compreensões. No entanto, tais compreensões não são incorporadas em seu escopo pai em tempo de execução. Patch por Jelle Zijlstra.

  • gh-118272: Corrige bug onde generator.close não libera os locais do quadro do gerador.

  • gh-118216: Não considera importações __future__ com pontos antes do nome do módulo.

  • gh-118074: Garante que os objetos Executor no array COLD_EXITS não sejam considerados GC-able (o que acessaria bytes fora do objeto).

  • gh-107674: Usa carregamento preguiçoso do número da linha do quadro para melhorar o desempenho do rastreamento

  • gh-118082: Melhora a mensagem SyntaxError para importações sem nomes, como nos casos from x import e import. Agora, ele indica aos usuários que import espera pelo menos um nome depois dele.

  • gh-118090: Melhora a mensagem SyntaxError para colchetes de parâmetros de tipo vazios.

  • gh-117958: Adicionado um método get_jit_code() para acessar o código de máquina compilado JIT do UOp Executor quando o JIT experimental estiver habilitado. Patch por Anthony Shaw.

  • gh-117901: Adiciona uma opção para o codegen do compilador para salvar sequências de instruções aninhadas para introspecção.

  • gh-116622: Redireciona stdout e stderr para o log do sistema quando incorporado em um aplicativo Android.

  • gh-109118: o escopo de anotação dentro de escopos de classe agora pode conter lambdas.

  • gh-117894: Impede que objetos agen.aclose() sejam reutilizados após .throw().

  • gh-117881: impede acesso simultâneo a um gerador assíncrono via athrow().throw() ou asend().throw()

  • gh-117536: Corrige um RuntimeWarning ao chamar agen.aclose().throw(Exception).

  • gh-117755: Corrige alocador mimalloc para alocação de memória enorme (em torno de 8.589.934.592 GiB) no s390x. Patch por Victor Stinner.

  • gh-117750: Corrige problema em que o dict de um objeto ficava fora de sincronia com os valores internos do objeto ao ser limpo. obj.__dict__.clear() agora limpa os valores internos, mas deixa o dict anexado ao objeto.

  • gh-117431: Melhora o desempenho dos seguintes métodos bytes e bytearray adaptando-os à convenção de chamada METH_FASTCALL:

    • count()

    • find()

    • index()

    • rfind()

    • rindex()

  • gh-117709: Acelera as chamadas para str() com argumento somente posicional, usando a convenção de chamada PEP 590 vectorcall. Patch por Erlend Aasland.

  • gh-117680: Dá a _PyInstructionSequence uma interface Python e use-a em testes.

  • gh-115776: Objetos alocados estaticamente são, por definição, imortais, portanto, devem ser marcados como tal, independentemente de estarem em módulos de extensão ou não.

  • gh-117385: Remove eventos PY_MONITORING_EVENT_BRANCH e PY_MONITORING_EVENT_EXCEPTION_HANDLED não manipulados de sys.settrace().

  • gh-116322: Módulos de extensão podem indicar ao tempo de execução que podem ser executados sem a GIL. Módulos init multifásicos fazem isso chamando o fornecimento de Py_MOD_GIL_NOT_USED para o slot Py_mod_gil, enquanto módulos init monofásicos chamam PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED) de sua função init.

  • gh-116129: Implementa PEP 696, adicionando suporte para padrões em parâmetros de tipo. Patch por Jelle Zijlstra.

  • gh-93502: Adiciona duas novas funções à API C, PyRefTracer_SetTracer() e PyRefTracer_GetTracer(), que permite rastrear a criação e destruição de objetos da mesma forma que o módulo tracemalloc faz. Patch por Pablo Galindo

  • gh-107674: Melhora significativamente o desempenho de sys.settrace()

  • gh-95754: Melhora a mensagem de erro quando um script que faz shadowing de um módulo da biblioteca padrão faz com que AttributeError seja levantada. Da mesma forma, melhorar a mensagem de erro quando um script que faz shadowing de um módulo de terceiros tenta acessar um atributo desse módulo de terceiros enquanto ainda está inicializando.

  • gh-99180: Elimina indicadores de traceback não informativos em instruções return e assignment simples. Patch por Pablo Galindo.

  • gh-105879: Permite que os argumentos globals e locals para exec() e eval() sejam passados como nomeados.

Biblioteca

  • gh-118418: Uma DeprecationWarning agora é emitida se você não passar um valor para o novo parâmetro type_params de typing._eval_type() ou typing.ForwardRef._evaluate(). (Usar qualquer uma dessas funções privadas e não documentadas é desencorajado para começar, mas deixar de passar um valor para o parâmetro type_params pode levar a um comportamento incorreto no Python 3.12 ou mais recente.)

  • gh-118660: Adiciona um segundo parâmetro de tipo opcional para typing.ContextManager e typing.AsyncContextManager, representando os tipos de retorno de __exit__() e __aexit__() respectivamente. Este parâmetro tem como padrão bool | None.

  • gh-118650: O módulo enum permite que o método chamado _repr_* seja definido em tipos Enum.

  • gh-118648: Adiciona padrões de parâmetros de tipo para typing.Generator e typing.AsyncGenerator.

  • gh-101137: O tipo MIME text/x-rst agora é suportado por mimetypes.

  • gh-118164: A implementação Python do módulo decimal poderia parecer travar em casos de potência relativamente pequena (como 2**117) se a precisão do contexto fosse definida como um valor muito alto. Um método diferente para verificar resultados exatamente representáveis é usado agora que não depende da computação de 10**precision (que poderia ser efetivamente muito grande para ser computada).

  • gh-111744: breakpoint() e pdb.set_trace() agora entram no depurador imediatamente após a chamada, em vez de antes da próxima linha ser executada.

  • gh-118500: Adiciona suporte pdb para zipapps

  • gh-118406: Adiciona assinatura para objetos sqlite3.Connection.

  • gh-101732: Usa uma função de tempo openssl compatível com Y2038 quando disponível.

  • gh-118404: Corrige inspect.signature() para chamáveis não comparáveis.

  • gh-118402: Corrige inspect.signature() para o resultado da chamada functools.cmp_to_key().

  • gh-116622: No Android, sysconfig.get_platform agora retorna o formato especificado por PEP 738.

  • gh-118285: Permite especificar a assinatura de instâncias personalizadas do tipo de extensão pelo atributo __text_signature__. Especifica assinaturas de instâncias operator.attrgetter, operator.itemgetter e operator.methodcaller.

  • gh-118314: Corrige um caso extremo no modo estrito binascii.a2b_base64(), onde o preenchimento excessivo não é detectado quando nenhum preenchimento é necessário.

  • gh-118271: Adiciona os métodos PhotoImage read() para ler uma imagem de um arquivo e data() para obter os dados da imagem. Adiciona os parâmetros background e grayscale ao método write() de PhotoImage.

  • gh-118225: Adiciona o método PhotoImage copy_replace() para copiar uma região de uma imagem para outra, possivelmente com zoom de pixel e/ou subamostragem. Adicione o parâmetro from_coords aos métodos copy(), zoom() e subsample() da PhotoImage. Adiciona os parâmetros zoom e subsample ao método copy() de PhotoImage.

  • gh-118221: Corrige um bug em que sqlite3.Connection.iterdump() poderia falhar se um row factory personalizado fosse usado. Patch por Erlend Aasland.

  • gh-118013: Corrige regressão introduzida em gh-103193 que significava que chamar inspect.getattr_static() em uma instância faria com que uma referência forte à classe dessa instância persistisse em um cache interno no módulo inspect. Isso causava consumo inesperado de memória se a classe fosse criada dinamicamente, a classe mantivesse referências fortes a outros objetos que ocupassem uma quantidade significativa de memória e o cache contivesse a única referência forte à classe. A correção para a regressão leva a uma lentidão em getattr_static(), mas a função ainda deve ser significativamente mais rápida do que era no Python 3.11. Patch por Alex Waygood.

  • gh-118218: Acelera itertools.pairwise() no caso comum em até 1,8x.

  • gh-117486: Melhora o comportamento das subclasses definidas pelo usuário de ast.AST. Essas classes agora não exigirão alterações no caso usual para estar em conformidade com as alterações de comportamento do módulo ast no Python 3.13. Patch por Jelle Zijlstra.

  • gh-90848: Corrigida unittest.mock.create_autospec() para configurar o mock pai com argumentos nomeados.

  • gh-118168: Corrige a substituição incorreta de argumentos quando typing.Unpack é usado com a tuple embutido. typing.Unpack agora levanta TypeError quando usado com certos tipos inválidos. Patch por Jelle Zijlstra.

  • gh-118131: Adiciona a interface de linha de comando para o módulo random. Patch por Hugo van Kemenade.

  • gh-118107: Corrige zipimport leitura de arquivos ZIP64 com entradas de arquivo muito grandes ou muito deslocadas.

  • gh-102511: Corrige os.path.normpath() para caminhos UNC no Windows. Acelera os.path.splitroot() com uma implementação nativa.

  • gh-117535: Altera o nome de arquivo desconhecido de warnings de sys para <sys> para esclarecer que não é um nome de arquivo real.

  • gh-114053: Corrige NameError errôneo ao chamar typing.get_type_hints() em uma classe que fazia uso de parâmetros de tipo PEP 695 em um módulo que tinha from __future__ import annotations no topo do arquivo. Patch por Alex Waygood.

  • gh-116931: Adiciona verificação do parâmetro fileobj para tarfile.TarFile.addfile()

  • gh-117995: Não levanta DeprecationWarning quando uma sequência de parâmetros for usada para vincular marcadores de posição indexados e sem nome. Veja também gh-100668.

  • gh-80361: Corrige TypeError em email.message.Message.get_payload() quando o charset é codificado em RFC 2231.

  • gh-86650: Corrige IndexError ao analisar alguns e-mails com Message-ID inválido (incluindo endereços únicos gerados pelo Microsoft Outlook).

  • gh-117691: Melhora as mensagens de erro emitidas pelos avisos de descontinuação de tarfile relacionados ao PEP 706. Se um argumento filter não for fornecido para extract() ou extractall, o aviso de descontinuação agora aponta para a linha no código do usuário onde a função relevante foi chamada. Patch por Alex Waygood.

  • gh-115874: Corrige um possível segfault durante a coleta de lixo de objetos _asyncio.FutureIter. Patch por Savannah Ostrowski.

  • gh-115060: Acelera pathlib.Path.glob() omitindo uma chamada inicial is_dir(). Como resultado dessa alteração, glob() não pode mais levantar OSError.

  • gh-77102: O módulo site agora analisa o arquivo .pth com UTF-8 primeiro, e codificação da localidade se UnicodeDecodeError acontecer. Ele suportava apenas codificação da localidade antes.

  • gh-76785: Nós expusemos o módulo de baixo nível _interpreters para o bem da implementação PyPI de PEP 734. Às vezes, ele estava disponível como o módulo _xxsubinterpreters e era usado anteriormente apenas para testes. Na maior parte, ele deve ser considerado um módulo interno, como _thread e _imp. Veja https://discuss.python.org/t/pep-734-multiple-interpreters-in-the-stdlib/41147/26.

  • gh-115060: Acelera pathlib.Path.glob() não escaneando diretórios para segmentos de padrões não curinga.

  • gh-117727: Acelera pathlib.Path.iterdir() usando os.scandir() internamente.

  • gh-117586: Acelera pathlib.Path.walk() trabalhando com strings internamente.

  • gh-117722: Altera o novo suporte a múltiplos separadores em asyncio.StreamReader.readuntil() para aceitar apenas tuplas de separadores em vez de iteráveis arbitrários.

  • gh-117692: Corrige um bug quando doctest.DocTestFinder estava falhando em builtin_function_or_method encapsulado.

  • gh-117348: Desempenho de tempo de importação amplamente restaurado do configparser evitando dataclasses.

  • gh-117641: Aceleração de os.path.commonpath() no Unix.

  • gh-117663: Corrige _simple_enum para detectar apelidos quando vários argumentos estão presentes, mas apenas um é o valor do membro.

  • gh-117636: Aceleração de os.path.join().

  • gh-117618: Suporte a package.module como filename para o comando break de pdb

  • gh-102247: os códigos de status enum com constantes em http.HTTPStatus são atualizados para incluir os nomes do RFC9110. Este RFC inclui alguns status HTTP usados anteriormente apenas para WEBDAV e atribui nomes mais genéricos a eles.

    As constantes antigas são preservadas para retrocompatibilidade.

  • gh-117607: Aceleração de os.path.relpath().

  • gh-117586: Aceleração de pathlib.Path.glob() trabalhando com strings internamente.

  • gh-117225: Adiciona cor à saída do doctest. Patch por Hugo van Kemenade.

  • gh-117566: ipaddress.IPv6Address.is_loopback() agora retornará True para endereços de loopback mapeados em IPv4, ou seja, endereços no espaço de endereço ::ffff:127.0.0.0/104.

  • gh-117546: Corrige o problema em que os.path.realpath() parou de resolver links simbólicos após encontrar um loop de links simbólicos no POSIX.

  • gh-116720: Comportamento aprimorado de asyncio.TaskGroup quando um cancelamento externo colide com um cancelamento interno. Por exemplo, quando dois grupos de tarefas são aninhados e ambos experimentam uma exceção em uma tarefa filha simultaneamente, era possível que o grupo de tarefas externo se comportasse mal, porque seu cancelamento interno foi engolido pelo grupo de tarefas interno.

    No caso em que um grupo de tarefas é cancelado externamente e também deve levantar uma ExceptionGroup, ele agora chamará o método cancel() da tarefa pai. Isso garante que uma asyncio.CancelledError será levantada no próximo await, para que o cancelamento não seja perdido.

    Um benefício adicional dessas mudanças é que os grupos de tarefas agora preservam a contagem de cancelamentos (asyncio.Task.cancelling()).

    Para lidar com alguns casos extremos, asyncio.Task.uncancel() agora pode redefinir o sinalizador não documentado _must_cancel quando a contagem de cancelamentos chegar a zero.

  • gh-117516: Adiciona typing.TypeIs, implementando PEP 742. Patch por Jelle Zijlstra.

  • gh-117503: Corrige suporte de nomes de usuários não-ASCII em caminhos de bytes em os.path.expanduser() no Posix.

  • gh-117394: os.path.ismount() agora é 2-3 vezes mais rápido se o usuário tiver permissões.

  • gh-117313: Trata apenas '\\n', '\\r' e '\\r\\n' como separadores de linha ao redobrar as mensagens email. Preserva os caracteres de controle '\\v', '\\f', '\\x1c', '\\x1d' e '\\x1e' e os separadores de linha Unicode '\\x85', '\\u2028' e '\\u2029' como estão.

  • gh-117142: Converte _ctypes para inicialização multifásica (PEP 489).

  • gh-66543: Adiciona a função mimetypes.guess_file_type() que funciona com o caminho do arquivo. Passar o caminho do arquivo em vez da URL em guess_type() está suavemente descontinuado.

  • gh-68583: CLI de webbrowser: substitui getopt por argparse, adiciona opções longas. Patch de Hugo van Kemenade.

  • gh-116871: Sugestões de nome para AttributeError e ImportError agora incluem apenas nomes sublinhados se o nome original estiver sublinhado.

  • gh-116023: Não mostra campos vazios (valor None ou []) em ast.dump() por padrão. Adiciona o parâmetro show_empty=False para mostrá-los opcionalmente.

  • gh-115961: Adicionados atributos name e mode para objetos arquivo ou similares compactados e arquivados nos módulos bz2, lzma, tarfile e zipfile. O valor do atributo mode de gzip.GzipFile foi alterado de inteiro (1 ou 2) para string ('rb' ou 'wb'). O valor do atributo mode do objeto arquivo ou similar legível retornado por zipfile.ZipFile.open() foi alterado de 'r' para 'rb'.

  • gh-82062: Corrige inspect.signature() para manipular corretamente os padrões de parâmetros em métodos em módulos de extensão que usam nomes definidos no espaço de nomes do módulo.

  • gh-83856: Honra atexit para todos os métodos de inicialização multiprocessing

  • gh-113081: Imprime exceção colorida assim como o traceback embutido em pdb

  • gh-112855: Acelera a serialização com pickle de objetos pathlib.PurePath. Patch por Barney Gale.

  • gh-111744: Suporte a eventos de opcode em bdb

  • gh-109617: ncurses: corrigiu uma falha que poderia ocorrer no macOS 13 ou anterior quando o Python era criado com o SDK do Apple Xcode 15.

  • gh-83151: Ativadas declarações e avaliações arbitrárias no shell pdb para acessar as variáveis locais do quadro atual, o que tornou possível que códigos multiescopo, como geradores ou funções aninhadas, funcionassem.

  • gh-110209: Adicionado __class_getitem__() a types.GeneratorType e types.CoroutineType para fins de dicas de tipo. Patch por James Hilton-Balfe.

  • gh-108191: O types.SimpleNamespace agora aceita um argumento posicional opcional que especifica valores iniciais de atributos como um dict ou um iterável de pares de chave-valor.

  • gh-62090: Corrige erros de asserção causados por espaços em branco em metavars ou grupos suprimidos com SUPPRESS em argparse simplificando a formatação de uso. Patch por Ali Hamdan.

  • gh-102402: Ajusta logging.LogRecord para usar time.time_ns() e corrige um pequeno bug relacionado à matemática de ponto flutuante.

  • gh-100242: Traz a implementação Python pura functools.partial.__new__ mais alinhada com a implementação C ao não apenas verificar sempre a presença do atributo 'func' no primeiro argumento de partial. Em vez disso, tanto a versão Python quanto a versão C realizam uma verificação isinstance(func, partial) no primeiro argumento de partial.

  • gh-99730: Solicitações HEAD não são mais atualizadas para solicitações GET durante redirecionamentos em urllib.

  • gh-66410: Define o módulo global wantobjects tkinter como 2 antes de criar o objeto Tk ou chamar o método wantobjects() do objeto Tk com o argumento 2 agora faz com que argumentos para retornos de chamada registrados no módulo tkinter sejam passados como vários objetos Python (int, float, bytes, tuple), dependendo de sua representação interna em Tcl, em vez de sempre str. tkinter.wantobjects agora está definido como 2 por padrão.

  • bpo-40943: Corrige vários IndexError ao analisar e-mails com Message-ID, endereço, rotas, etc. truncados, por exemplo, example@.

  • bpo-39324: Adiciona mapeamento de tipo mime para .md <-> text/markdown

  • bpo-18108: shutil.chown() agora suporta argumentos nomeados dir_fd e follow_symlinks.

  • bpo-30988: Corrige análise de e-mails com cabeçalhos de endereço inválidos com um ponto inicial ou final. Patch por tsufeki.

  • bpo-32839: Adiciona o método after_info() para widgets Tkinter.

Documentação

  • gh-117928: A versão mínima do Sphinx necessária para a documentação agora é 6.2.1.

Construção

  • gh-118734: Corrige a construção do Windows quando invocada diretamente (não por meio do script build.bat) sem especificar um valor para UseTIER2.

  • gh-115119: The configure option --with-system-libmpdec now defaults to yes. The bundled copy of libmpdecimal will be removed in Python 3.15.

  • gh-117845: Corrige a construção em versões recentes do libedit detectando assinaturas de hook readline em configure.

  • gh-116622: Um projeto de testbed foi adicionado para executar o conjunto de testes no Android.

  • gh-117645: Aumenta o tamanho da pilha WASI de 512 KiB para 8 MiB e a memória inicial de 10 MiB para 20 MiB. Patch por Victor Stinner.

  • gh-115119: configure now uses pkg-config to detect decimal dependencies if the --with-system-libmpdec option is given.

Windows

  • gh-115119: Atualiza o instalador do Windows para usar libmpdecimal 4.0.0.

  • gh-118486: os.mkdir() agora aceita modo de 0o700 para restringir o novo diretório ao usuário atual.

  • gh-118347: Corrige atualizações do iniciador que não sendo instaladas.

  • gh-118293: O módulo multiprocessing agora passa o sinalizador STARTF_FORCEOFFFEEDBACK ao gerar processos para informar ao Windows para não alterar o cursor do mouse.

  • gh-115009: Atualiza o instalador do Windows para usar o SQLite 3.45.3.

  • gh-90329: Suprime o aviso exibido na criação do ambiente virtual quando os caminhos solicitados e criados diferem apenas por um nome curto (estilo 8.3). Os avisos continuarão a ser exibidos se uma junção ou link simbólico no caminho fez com que o venv fosse criado em um local diferente do solicitado originalmente.

  • gh-117786: Corrige ambientes virtuais que não iniciam corretamente quando criados a partir de uma instalação da Store.

macOS

  • gh-115119: Atualiza o instalador do macOS para usar libmpdecimal 4.0.0.

  • gh-114099: O uso do símbolo do pré-processador iOS foi tornado compatível com SDKs macOS mais antigos.

  • gh-115009: Atualiza o instalador macOS para usar o SQLite 3.45.3.

  • gh-91629: Use as configurações ~/.config/fish/conf.d e fish_add_path para definir PATH ao instalar para o shell Fish.

IDLE

  • bpo-34774: Use o tema de cores selecionado pelo usuário para Help => IDLE Doc.

API C

  • gh-118124: Corrige Py_BUILD_ASSERT e Py_BUILD_ASSERT_EXPR para expressões não constantes: use static_assert() no C11 e mais recentes. Patch por Victor Stinner.

  • gh-110850: Adiciona variante “Raw” das funções PyTime

    Patch por Victor Stinner.

  • gh-117987: Restaura funções removidas no Python 3.13 alpha 1:

    • Py_SetPythonHome()

    • Py_SetProgramName()

    • PySys_SetArgvEx()

    • PySys_SetArgv()

    Patch por Victor Stinner.

  • gh-117929: Restaura função removida PyEval_InitThreads(). Patch por Victor Stinner.

  • gh-117534: Melhora a lógica de validação na implementação C de datetime.datetime.fromisoformat() para lidar melhor com anos inválidos. Patch por Vlad Efanov.

  • gh-68114: Corrigido o tratamento de skipitem() dos antigos formatadores ‘w’ e ‘w#’. Eles não são mais suportados e agora levantam uma exceção se usados.

  • gh-111997: Adiciona uma API C para disparar eventos de monitoramento.

Python 3.13.0 alpha 6

Data de lançamento: 2024-04-09

Núcleo e embutidos

  • gh-117494: Refatorada a estrutura de dados da sequência de instruções de compile.c para instruction_sequence.c.

  • gh-116968: Introduzido um tipo de contador de backoff unificado de 16 bits (_Py_BackoffCounter), compartilhado entre o especializador adaptativo de Nível 1 e o otimizador de Nível 2. A API usada para contadores de especialização adaptável é alterada, mas o comportamento é (supostamente) idêntico.

    O comportamento dos contadores de Nível 2 é alterado:

    • Não há mais limites dinâmicos (nunca os variamos).

    • Todos os contadores agora usam o mesmo backoff exponencial.

    • O contador para JUMP_BACKWARD começa a contagem regressiva a partir de 16.

    • A temperature nas saídas laterais começa a contagem regressiva a partir de 64.

  • gh-117431: Melhora o desempenho dos seguintes métodos bytes e bytearray adaptando-os à convenção de chamada METH_FASTCALL:

    • endswith()

    • startswith()

  • gh-117431: Melhora o desempenho dos seguintes métodos str adaptando-os à convenção de chamada METH_FASTCALL:

  • gh-117411: Move PyFutureFeatures para um cabeçalho interno e torna-o privado.

  • gh-109120: Adicionado identificador de expressões de estrela incorretas, por exemplo f(3, *). Patch por Grigoryev Semyon

  • gh-117266: Corrige travamentos para certas subclasses criadas pelo usuário de ast.AST. Essas classes agora devem definir o atributo _field_types.

  • gh-99108: Atualizado o código C do projeto HACL* do hashlib embutido a partir do upstream que usamos para muitas implementações quando elas não estão presentes via OpenSSL em uma determinada construção. Isso também evita o raro potencial de um problema de vinculação de regra de definição de nome de símbolo C.

  • gh-117108: Altera o antigo bit de espaço de objetos na geração jovem de 0 para gcstate->visited, para que quaisquer objetos criados durante o GC tenham o antigo bit definido corretamente se forem movidos para a geração antiga.

  • gh-117108: O GC do ciclo agora escolhe o tamanho dos incrementos com base no tamanho total do heap, em vez da taxa de criação de objetos. Isso garante que ele possa acompanhar o crescimento dos heaps.

  • gh-116735: Para INSTRUMENTED_CALL_FUNCTION_EX, define arg0 como sys.monitoring.MISSING em vez de None para o evento CALL.

  • gh-113964: Iniciar novas threads e a criação de processos por meio de os.fork() agora são impedidos somente quando todas as threads não daemon são encerradas.

  • gh-116626: Garante que INSTRUMENTED_CALL_FUNCTION_EX sempre emita CALL

  • gh-116554: list.sort() agora explora mais casos de ordenação parcial, particularmente aqueles com longas execuções descendentes com subexecuções de valores iguais. Elas são reconhecidas como execuções únicas agora (anteriormente, cada bloco de valores repetidos fazia com que uma nova execução fosse criada).

  • gh-114099: Adicionado um carregador que pode descobrir módulos de extensão em uma pasta Frameworks no estilo iOS.

  • gh-115775: O compilador preenche o novo campo __static_attributes__ em uma classe com os nomes dos atributos desta classe que são acessados por meio de self.X de qualquer função em seu corpo.

  • gh-115776: A array de valores, a estrutura PyDictValues agora é incorporada ao objeto durante a alocação. Isso fornece melhor desempenho no caso comum e não degrada tanto quando o __dict__ do objeto é materializado.

  • gh-108362: Implementa um coletor de lixo cíclico incremental. Ao coletar a geração antiga em incrementos, não há necessidade de uma varredura completa do heap. Isso pode reduzir enormemente o tempo máximo de pausa para programas com grandes heaps.

    Reduz o número de gerações de três para duas. A geração antiga é dividida em dois espaços, “visitado” e “pendente”.

    A coleta acontece em duas etapas:: * Um incremento é formado a partir da geração jovem e uma pequena parte do espaço pendente. * Este incremento é escaneado e os sobreviventes são movidos para o final do espaço visitado.

    Quando o espaço de coleta fica vazio, os dois espaços são trocados.

Biblioteca

  • gh-109870: Dataclasses agora chamam exec() uma vez por dataclass, em vez de uma vez por método adicionado. Isso pode acelerar a criação de dataclass em até 20%.

  • gh-97901: O tipo MIME text/rtf agora é suportado por mimetypes.

Núcleo e embutidos

  • bpo-24612: Melhora o SyntaxError que acontece quando ‘not’ aparece após um operador. Patch por Pablo Galindo

Biblioteca

  • gh-117648: Melhora o desempenho de os.path.join() e os.path.expanduser().

  • gh-117584: Raise TypeError for non-paths in posixpath.relpath.

  • gh-117467: Preserve mailbox ownership when rewriting in mailbox.mbox.flush. Patch by Tony Mountifield.

  • gh-114848: Levanta FileNotFoundError quando getcwd() retornar ‘(unreachable)’, o que pode acontecer no Linux >= 2.6.36 com glibc < 2.27.

  • gh-117459: asyncio.asyncio.run_coroutine_threadsafe() agora mantém o traceback de CancelledError, TimeoutError e InvalidStateError que são levantados na corrotina.

  • gh-117381: Corrige mensagem de erro para ntpath.commonpath().

  • gh-117337: Descontinua funções não documentadas glob.glob0() e glob.glob1(). Use glob.glob() e passe um diretório para seu argumento root_dir.

  • gh-117349: Otimiza várias funções em os.path.

  • gh-117348: Refatorado configparser.RawConfigParser._read() para reduzir a complexidade ciclométrica e melhorar a compreensão.

  • gh-117335: Levanta TypeError para não sequências para ntpath.commonpath().

  • gh-66449: configparser.ConfigParser agora aceita seções sem nome antes das nomeadas, se configurado para isso.

  • gh-88014: Na documentação de gzip.GzipFile no módulo gzip, explique o tipo de dados do argumento construtor opcional mtime e recomende mtime = 0 para gerar fluxos determinísticos.

  • gh-117310: Corrigida uma falha improvável inicial e extra Py_DECREF em ssl ao criar um novo _ssl._SSLContext se o CPython foi construído de forma implausível, de modo que a lista de cifras padrão está vazia ou a biblioteca SSL à qual foi vinculado relata uma falha de sua API C SSL_CTX_set_cipher_list().

  • gh-117294: Um DocTestCase agora relata como ignorado se todos os exemplos no doctest forem ignorados.

  • gh-98966: Em subprocess, levanta uma mensagem mais informativa quando stdout=STDOUT.

  • gh-117225: doctest: imprime apenas “e X failed” quando não for zero, não pluraliza “1 items”. Patch de Hugo van Kemenade.

  • gh-117205: Acelera compileall.compile_dir() em 20% ao usar multiprocessamento aumentando chunksize.

  • gh-117178: Corrige a regressão no carregamento lento de módulos autorreferenciais, introduzida em gh-114781.

  • gh-112383: Corrige o tratamento do módulo dis de instruções ENTER_EXECUTOR.

  • gh-117182: O carregamento preguiçoso de módulos que modificam seu próprio __class__ não reverte mais o __class__ para types.ModuleType.

  • gh-117084: Corrige a extração de zipfile para entradas de diretório com o nome contendo barras invertidas no Windows.

  • gh-117114: Torna os.path.isdevdrive() disponível em todas as plataformas. Para aqueles que não oferecem Dev Drives, ele sempre retornará False.

  • gh-117110: Corrige um bug que impede que subclasses de typing.Any sejam instanciadas com argumentos. Patch por Chris Fu.

  • gh-109653: Adiadas as importações de seleção em importlib.metadata e importlib.resources para uma aceleração de 14%.

  • gh-70647: Inicia o período de descontinuação para o comportamento atual de datetime.datetime.strptime() e time.strptime() que sempre falha ao analisar uma sequência de datas com um ValueError envolvendo um dia do mês, como strptime("02-29", "%m-%d") quando um ano não é especificado e a data acontece de ser 29 de fevereiro. Isso deve ajudar a evitar que os usuários encontrem novos bugs a cada quatro anos devido a uma suposição natural equivocada sobre a API ao analisar valores de data parciais.

  • gh-116987: Corrigida inspect.findsource() para objetos de código de classe.

  • gh-114099: Modifica a biblioteca padrão para permitir diferenças de plataforma iOS.

  • gh-90872: No Windows, subprocess.Popen.wait() não chama mais WaitForSingleObject() com um tempo limite negativo: passe 0 ms se o tempo limite for negativo. Patch por Victor Stinner.

  • gh-116957: configparser: Não deixa os valores ConfigParser em um estado inválido (armazenados como uma lista em vez de uma str) após uma leitura anterior gerar DuplicateSectionError ou DuplicateOptionError.

  • gh-115538: _io.WindowsConsoleIO agora emite um aviso se um valor booleano for passado como um argumento filedescriptor.

  • gh-90095: Ignora linhas vazias e comentários em .pdbrc

  • gh-106531: Atualizado zipfile._path de zipp 3.18, fornecendo melhor compatibilidade para PyPy, melhor desempenho glob para arquivos zip profundamente aninhados e fornecendo acesso interno a CompleteDirs.inject para uso em outros testes (como importlib.resources).

  • gh-63207: No Windows, time.time() agora usa o relógio GetSystemTimePreciseAsFileTime() para ter uma resolução melhor que 1 us, em vez do relógio GetSystemTimeAsFileTime() que tem uma resolução de 15,6 ms. Patch por Victor Stinner.

  • gh-116764: Restaura o suporte de None e outros valores falsos nas funções urllib.parse parse_qs() e parse_qsl(). Além disso, agora eles levantam um TypeError para inteiros diferentes de zero e sequências não vazias.

  • gh-116811: Em PathFinder.invalidate_caches, delega para MetadataPathFinder.invalidate_caches.

  • gh-116647: Corrige filho recursivo em dataclasses

  • gh-113171: Corrige vários falsos positivos e falsos negativos em

    Também nos atributos correspondentes ipaddress.IPv4Network e ipaddress.IPv6Network.

  • gh-63283: Em encodings.idna, qualquer capitalização do prefixo ACE (xn--) agora é aceitável. Patch por Pepijn de Vos e Zackery Spytz.

  • gh-71042: Adiciona platform.android_ver(), que fornece informações sobre o dispositivo e o sistema operacional no Android.

  • gh-73468: Adicionada a nova função math.fma(), envolvendo a operação fma() do C99: função de multiplicação-adição fundida. Patch por Mark Dickinson e Victor Stinner.

  • gh-116608: As funções importlib.resources is_resource(), open_binary(), open_text(), path(), read_binary() e read_text() não estão mais descontinuadas e oferecem suporte a subdiretórios por meio de vários argumentos posicionais. A função contents() também permite subdiretórios, mas continua descontinuada.

  • gh-116484: Altera os nomes de widgets tkinter.Checkbutton gerados automaticamente para evitar colisões com nomes de widgets tkinter.ttk.Checkbutton gerados automaticamente dentro do mesmo widget pai.

  • gh-114314: Em ctypes, os dados de ctype agora são armazenados em objetos type diretamente em vez de em uma subclasse dict. Esta é uma alteração interna que não deve afetar o uso.

  • gh-116401: Corrige o bloqueio de os.fwalk() e shutil.rmtree() ao abrir o encadeamento nomeado.

  • gh-71052: Implementa ctypes.util.find_library() no Android.

  • gh-90535: Corrige suporte de valores de interval > 1 em logging.TimedRotatingFileHandler para when='MIDNIGHT' e when='Wx'.

  • gh-113308: Remove algumas partes internas protegidas de uuid: _has_uuid_generate_time_safe, _netbios_getnode, _ipconfig_getnode e _load_system_functions. Elas não eram usadas.

  • gh-115627: Corrige o tratamento de erro do módulo ssl de término de conexão por peer. Agora ele lança um OSError com o código de erro apropriado em vez de um EOFError.

  • gh-114847: Acelera os.path.realpath() em plataformas não Windows.

  • gh-114271: Corrige uma corrida em threading.Thread.join().

    threading._MainThread agora sempre representa o thread principal do interpretador principal.

    PyThreadState.on_delete e PyThreadState.on_delete_data foram removidos.

  • gh-113538: Adiciona os métodos asyncio.Server.close_clients() e asyncio.Server.abort_clients() que permitem fechar um servidor asyncio de forma mais forçada.

  • gh-85287: Altera os codecs Unicode para retornar UnicodeEncodeError ou UnicodeDecodeError, em vez de apenas UnicodeError.

  • gh-113548: pdb agora permite argumentos CLI para pdb -m.

  • gh-112948: Torna a conclusão de pdb semelhante ao Python REPL

  • gh-105866: Corrigido o bug _get_slots que causava erro ao definir dataclasses com slots e um weakref_slot.

  • gh-96471: Adiciona a terminação asyncio.Queue com o método shutdown().

  • gh-89739: O módulo zipimport agora pode ler arquivos ZIP64.

  • bpo-33533: asyncio.as_completed() agora retorna um objeto que é um iterador assíncrono e um iterador simples. O novo padrão de iteração assíncrona permite uma correlação mais fácil entre tarefas anteriores e seus resultados concluídos. Esta é uma correspondência mais próxima ao padrão de iteração de concurrent.futures.as_completed(). Patch por Justin Arthur.

  • bpo-27578: inspect.getsource() (e funções relacionadas) funcionam com arquivos de módulo vazios, retornando '\\n' (ou equivalente razoável) em vez de gerar OSError. Patch por Kernc.

  • bpo-37141: Aceita um iterável de separadores em asyncio.StreamReader.readuntil(), parando quando um deles for encontrado.

  • gh-66543: Faz mimetypes.guess_type() analisar corretamente URLs com apenas um nome de host, URLs contendo fragmento ou consulta e nomes de arquivo com apenas um sharepoint UNC no Windows. Baseado no patch por Dong-hee Na.

  • bpo-15010: unittest.TestLoader.discover() agora salva o valor original de unittest.TestLoader._top_level_dir e o restaura no final da chamada.

Documentação

  • gh-115977: Remove referências de compatibilidade para Emscripten.

  • gh-114099: Adiciona um guia de plataforma iOS e sinaliza módulos não disponíveis no iOS.

  • gh-91565: Alterações nos arquivos de documentação e saídas de configuração para refletir o novo local para relatar bugs - ou seja, GitHub em vez de bugs.python.org.

Testes

  • gh-83434: Desativa a saída XML do JUnit (opção de linha de comando --junit-xml=FILE) no regrtest ao procurar vazamentos de referência (opção -R). Patch por Victor Stinner.

  • gh-117187: Corrige testes XML para vanilla Expat <2.6.0.

  • gh-116333: Testes de coisas relacionadas a TLS (códigos de erro, etc.) foram atualizados para serem mais tolerantes sobre strings e comportamentos de mensagens de erro específicos, como visto nos forks BoringSSL e AWS-LC do OpenSSL.

  • gh-117089: Testes consolidados para importlib.metadata em seu próprio pacote metadata.

  • gh-115979: Atualiza test_importlib para que passe no WASI SDK 21.

  • gh-112536: Adiciona –tsan ao test.regrtest para executar testes TSAN em tempos de execução razoáveis. Patch por Donghee Na.

  • gh-116307: Adicionado o auxiliar de importação isolated_modules, pois CleanImport não remove módulos importados durante o contexto. Use-o em testes importlib.resources para evitar deixar mod por aí para impedir testes importlib.metadata.

Construção

  • gh-114736: Faz construções WASI usar WASI SDK 21.

  • gh-115983: Pula a construção de módulos de teste que devem ser construídos como compartilhados sob WASI.

  • gh-71052: Adiciona script de construção e instruções do Android.

Windows

  • gh-117267: Garante que DirEntry.stat().st_ctime se comporte consistentemente com os.stat() durante o período de descontinuação de st_ctime contendo o mesmo valor que st_birthtime. Após o período de descontinuação, st_ctime será o tempo de alteração de metadados (ou indisponível por meio de DirEntry), e apenas st_birthtime conterá o tempo de criação.

  • gh-116195: Melhora o desempenho de os.getppid() usando uma API de sistema alternativa quando disponível. Contribuição de vxiiduu.

  • gh-88494: No Windows, time.monotonic() agora usa o relógio QueryPerformanceCounter() para ter uma resolução melhor que 1 us, em vez do relógio GetTickCount64() que tem uma resolução de 15,6 ms. Patch por Victor Stinner.

  • gh-116773: Corrige instâncias de <_overlapped.Overlapped object at 0xXXX> still has pending operation at deallocation, the process may crash.

  • gh-91227: Corrige a implementação asyncio ProactorEventLoop para que o envio de um datagrama para um endereço que não esteja escutando não impeça o recebimento de mais datagramas.

  • gh-115119: Trocado do código libmpdecimal fornecido para um pacote externo hospedado separadamente no repositório cpython-source-deps ao construir o módulo _decimal.

API C

  • gh-117642: Corrige a implementação de PEP 737 para %#T e %#N.

  • gh-87193: _PyBytes_Resize() agora pode ser chamada para objetos bytes com contagem de referências > 1, incluindo objetos bytes de 1 byte. Ele cria um novo objeto bytes e destrói o antigo se ele tiver contagem de referências > 1.

  • gh-117021: Corrige estouro de inteiro em PyLong_AsPid() em plataformas de 64 bits que não sejam Windows.

  • gh-115756: PyCode_GetFirstFree() é uma API utilizável agora e foi renomeada para PyUnstable_Code_GetFirstFree(). (Contribuição de Bogdan Romanyuk em gh-115781)

  • gh-116869: Adiciona o teste test_cext: cria uma extensão C para verificar se a API Python C emite avisos do compilador C. Patch por Victor Stinner.

  • gh-116869: Torna a API C compatível com o sinalizador do compilador -Werror=declaration-after-statement novamente. Patch por Victor Stinner.

  • gh-116936: Adiciona PyType_GetModuleByDef() à API C limitada. Patch por Victor Stinner.

  • gh-116809: Restaura a função privada _PyErr_ChainExceptions1() removida. Patch por Victor Stinner.

  • gh-115754: Na versão limitada 3.13 da API C, obter Singletons Py_None, Py_False, Py_True, Py_Ellipsis e Py_NotImplemented agora é implementado como chamadas de função no nível ABI estável para ocultar detalhes de implementação. Obter essas constantes ainda retorna referências emprestadas. Patch por Victor Stinner.

  • gh-115754: Adiciona as funções Py_GetConstant() e Py_GetConstantBorrowed() para obter constantes. Por exemplo, Py_GetConstant(Py_CONSTANT_ZERO) retorna uma referência forte para a constante zero. Patch por Victor Stinner.

  • gh-111696: Adiciona suporte para os formatos %T, %T#, %N e %N# para PyUnicode_FromFormat(): formata o nome totalmente qualificado de um tipo de objeto e de um tipo: chama PyType_GetModuleName(). Veja PEP 737 para mais informações. Patch por Victor Stinner.

  • gh-111696: Adiciona a função PyType_GetModuleName() para obter o nome do módulo do tipo. Equivalente a obter o atributo type.__module__. Patch por Eric Snow e Victor Stinner.

  • gh-111696: Adiciona a função PyType_GetFullyQualifiedName() para obter o nome totalmente qualificado do tipo. Equivalente a f"{type.__module__}.{type.__qualname__}", ou type.__qualname__ se type.__module__ não for uma string ou for igual a "builtins". Patch por Victor Stinner.

  • gh-85283: As extensões C fcntl, grp, pwd, termios, _statistics e _testconsole agora são construídas com a API C limitada. Patch por Victor Stinner.

  • gh-111140: Adiciona sinalizadores adicionais a PyLong_AsNativeBytes() e PyLong_FromNativeBytes() para permitir que o chamador determine como lidar com casos extremos em torno de valores que preenchem o buffer inteiro.

  • gh-113024: Adiciona a função PyObject_GenericHash().

Python 3.13.0 alpha 5

Data de lançamento: 2024-03-12

Segurança

Núcleo e embutidos

  • gh-116604: Respeita o status do coletor de lixo quando chamadas indiretas são feitas via PyErr_CheckSignals() e o disjuntor de avaliação. Patch por Pablo Galindo

  • gh-112087: list agora é compatível com a implementação da PEP 703.

  • gh-116381: Adiciona especialização para CONTAINS_OP.

  • gh-116296: Corrige possível vazamento de referência no tratamento de erros internos de object.__reduce__().

  • gh-115823: Calcula corretamente intervalos de erro no analisador ao levantar exceções SyntaxError causadas por sequências de bytes inválidas. Patch por Pablo Galindo

  • gh-115778: Adiciona anotação tierN para definição de instrução no interpretador DSL.

  • gh-115733: Corrige travamento ao chamar next() em iteradores de lista esgotados.

  • gh-115700: O estágio de construção de regen-cases agora funciona no Windows.

  • gh-115347: Corrige um bug em que docstring era substituído por um NOP redundante quando Python é executado com -OO.

  • gh-115323: Torna a mensagem de erro mais significativa para quando bytearray.extend() é chamado com um objeto str.

  • gh-112175: Cada PyThreadState agora tem seu próprio eval_breaker, permitindo que threads específicos sejam interrompidos.

Biblioteca

  • gh-115154: Corrige um bug que estava fazendo com que a função tokenize.untokenize() manipulasse literais nomeados unicode incorretamente. Patch por Pablo Galindo

Núcleo e embutidos

Biblioteca

  • gh-104090: O rastreador de recursos de multiprocessamento agora sai com código de status diferente de zero se um vazamento de recurso for detectado. Ele ainda sai com código de status 0 caso contrário.

Núcleo e embutidos

  • gh-105858: Melhora os construtores para nós ast. Os argumentos de tipos de lista agora assumem como padrão uma lista vazia se omitidos, e os campos opcionais assumem como padrão None. Os nós AST agora têm um atributo __annotations__ com os tipos esperados de seus atributos. Passar argumentos extras não reconhecidos para nós AST está descontinuado e se tornará um erro no Python 3.15. Omitir um argumento obrigatório para um nó AST está descontinuado e se tornará um erro no Python 3.15. Patch por Jelle Zijlstra.

  • gh-101860: Expor atributo __name__ na propriedade.

  • gh-96497: Corrige resolução incorreta de variáveis de classe mutiladas usadas em expressões de atribuição em compreensões.

Biblioteca

  • gh-116600: Corrige repr() para membros globais Flag.

  • gh-116349: platform.java_ver() está descontinuado e será removido na versão 3.15. Ele não foi testado em grande parte, tinha uma API confusa e era útil apenas para suporte a Jython.

  • gh-116143: Corrige uma corrida no pydoc _start_server, eliminando uma janela na qual _start_server pode retornar um thread que está “servindo”, mas sem um conjunto docserver.

  • gh-116127: typing: implementa PEP 705 que adiciona suporte a typing.ReadOnly para typing.TypedDict.

  • gh-116325: typing: levanta SyntaxError em vez de AttributeError em referências de encaminhamento como strings vazias.

  • gh-115957: Quando asyncio.TaskGroup.create_task é chamado em um asyncio.TaskGroup inativo, a corrotina fornecida será fechada (o que impede um RuntimeWarning).

  • gh-115978: Desabilita preadv(), readv(), pwritev() e writev() em WASI.

    No wasmtime para WASI 0.2, essas funções não passam no test_posix (https://github.com/bytecodealliance/wasmtime/issues/7830).

  • gh-88352: Corrige o cálculo do próximo tempo de rollover no manipulador logging.TimedRotatingFileHandler. computeRollover() agora sempre retorna um registro de data e hora maior que o tempo especificado e funciona corretamente durante a mudança de horário de verão. doRollover() não substitui mais o arquivo já rolado, evitando perda de dados quando executado à meia-noite ou durante tempo repetido na mudança de horário de verão.

  • gh-87115: Define __main__.__spec__ como None ao executar um script com pdb

  • gh-76511: Corrige UnicodeEncodeError em email.Message.as_string() que resulta quando uma mensagem que afirma estar no conjunto de caracteres ASCII na verdade tem caracteres não ASCII. Caracteres não ASCII agora são substituídos pelo caractere de substituição U+FFFD, como no manipulador de erros replace.

  • gh-89547: Adiciona suporte para formulários especiais de digitação aninhada como Final[ClassVar[int]].

  • gh-65824: Melhora o prompt less em pydoc.

  • gh-116040: [Enum] corrige chamadas por valor quando o segundo valor for falso; por exemplo. Cardinal(1, 0)

  • gh-115821: [Enum] Melhora a mensagem de erro ao chamar super().__new__() em __new__ personalizado.

  • gh-85644: Usa a variável de ambiente XDG_CURRENT_DESKTOP em webbrowser para verificar a área de trabalho. Prefira-a ao descontinuado GNOME_DESKTOP_SESSION_ID para detecção do GNOME.

  • gh-75988: Corrigida unittest.mock.create_autospec() para passar a chamada para o objeto encapsulado para retornar o resultado real.

  • gh-115881: Corrige problema em que ast.parse() sinalizaria incorretamente gerenciadores de contexto condicional (como with (x() if y else z()): ...) como sintaxe inválida se feature_version=(3, 8) fosse passado. Isso reverte as alterações na gramática feitas como parte de gh-94949.

  • gh-115886: Corrige truncamento silencioso do nome com um caractere nulo incorporado em multiprocessing.shared_memory.SharedMemory.

  • gh-115532: Adiciona estimativa de densidade do kernel ao módulo de estatísticas.

  • gh-115714: No WASI, o módulo time não obtém mais o tempo de processo usando times() ou CLOCK_PROCESS_CPUTIME_ID, a API do sistema não é confiável e provavelmente será removida do WASI. As funções de relógio afetadas retornam para chamar clock().

  • gh-115809: Melhora o algoritmo para calcular quais arquivos de log revertidos devem ser excluídos em logging.TimedRotatingFileHandler. Agora é confiável para manipuladores sem namer e com namer determinístico arbitrário que deixa a parte de data e hora no nome do arquivo inalterada.

  • gh-74668: As funções urllib.parse parse_qs() e parse_qsl() agora suportam argumentos de bytes contendo dados não ASCII brutos e codificados em porcentagem.

  • gh-67044: csv.writer() agora sempre coloca aspas ou escapa '\r' e '\n', independentemente do valor lineterminator.

  • gh-115712: Restaura o suporte do delimitador de espaço com skipinitialspace=True em csv. csv.writer() agora coloca aspas em campos vazios se o delimitador for um espaço e skipinitialspace for true e levanta uma exceção se aspas não forem possíveis.

  • gh-112364: Corrigido ast.unparse() para manipular format_spec com ", ' ou \\. Corrigido por Frank Hoffmann.

  • gh-112997: Para de registrar argumentos de retorno de chamada potencialmente sensíveis em asyncio a menos que o modo de depuração esteja ativo.

  • gh-114914: Corrige um problema em que um StreamWriter abandonado não seria coletado como lixo.

  • gh-111358: Corrige um bug em asyncio.BaseEventLoop.shutdown_default_executor() para garantir que o tempo limite passado para a corrotina se comporte conforme o esperado.

  • gh-115618: Corrige a diminuição inadequada da contagem de referência para o argumento None em métodos property getter(), setter() e deleter().

  • gh-112720: Refatora dis.ArgResolver para tornar possível fazer subclasse e alterar a maneira como argumentos de salto são interpretados.

  • gh-112006: Corrige inspect.unwrap() para tipos com o descritor de dados __wrapper__. Corrige inspect.Signature.from_callable() para embutido classmethod() e staticmethod().

  • gh-101293: Adiciona suporte a chamáveis com o método __call__() e tipos com métodos __new__() e __init__() definidos como métodos de classe, métodos estáticos, métodos vinculados, funções parciais e outros tipos de métodos e descritores em inspect.Signature.from_callable().

  • gh-103092: Isola _lsprof (aplica a PEP 687).

  • gh-113942: pydoc não ignora mais funções globais implementadas como métodos embutidos, como MethodDescriptorType e WrapperDescriptorType.

  • gh-115256: Adicionado DeprecationWarning ao acessar o atributo tarfile de objetos TarInfo. O atributo nunca é usado internamente e só é anexado ao TarInfos quando o tarfile é aberto no modo de gravação, não no modo de leitura. O atributo cria um ciclo de referência desnecessário que pode causar corrupção ao não fechar o identificador após gravar um tarfile.

  • gh-115197: urllib.request não resolve mais o nome do host antes de verificá-lo em relação à lista de bypass de proxy do sistema no macOS e Windows.

  • gh-113812: DatagramTransport.sendto() agora enviará datagramas de comprimento zero se for chamado com um objeto de bytes vazio. O controle de fluxo de transporte agora também considera o cabeçalho do datagrama ao calcular o tamanho do buffer.

  • gh-114763: Protege os módulos carregados com importlib.util.LazyLoader de condições de corrida quando vários threads tentam acessar atributos antes que o carregamento seja concluído.

  • gh-114709: posixpath.commonpath() agora levanta uma exceção ValueError quando passado um iterável vazio. Anteriormente, IndexError era levantada.

    posixpath.commonpath() agora levanta uma exceção TypeError quando passado None. Anteriormente, ValueError era levantada.

  • gh-114610: Corrige bug onde pathlib.PurePath.with_stem() convertia um sufixo de caminho não vazio em um radical quando recebia um argumento stem vazio. Agora levanta ValueError, assim como pathlib.PurePath.with_suffix() faz quando chamado em um caminho com um radical vazio, dado um argumento suffix não vazio.

  • gh-107361: Adiciona ssl.VERIFY_X509_PARTIAL_CHAIN e VERIFY_X509_STRICT ao contexto SSL padrão criado com ssl.create_default_context().

  • gh-112281: Permite a criação de união de tipos para typing.Annotated com metadados não-estruturáveis.

  • gh-111775: Corrige importlib.resources.simple.ResourceHandle.open() para modo texto, adicionado argumento stream ausente.

  • gh-90095: Faz .pdbrc e -c funcionarem com quaisquer comandos pdb válidos.

  • gh-107625: Levanta configparser.ParsingError dos métodos read() e read_file() de configparser.ConfigParser se uma chave sem um valor correspondente for continuada (isto é, seguida por uma linha indentada).

  • gh-107155: Corrige saída incorreta de help(x) onde x é uma função lambda, que tem um atributo de dicionário __annotations__ com uma chave "return".

  • gh-57141: Adiciona opção para comparações não rasas para filecmp.dircmp como filecmp.cmp(). Patch original por Steven Ward. Aprimorado por Tobias Rautenkranz

  • gh-69990: Profile.print_stats() foi melhorado para aceitar vários argumentos de classificação. Correção por Chiu-Hsiang Hsu e Furkan Onder.

  • gh-104061: Adiciona constante socket.SO_BINDTOIFINDEX.

  • gh-60346: Corrige ArgumentParser inconsistente com parse_known_args.

  • gh-102389: Adiciona windows_31j aos apelidos para o codec cp932

  • gh-72249: Always include the module name in the repr() of functools.partial() objects. Patch by Furkan Onder and Anilyka Barry.

  • gh-100985: Atualiza HTTPSConnection para encapsular consistentemente endereços IPv6 ao usar um proxy.

  • gh-100884: email: corrige dobramento incorreto de vírgula em listas de endereços em várias linhas em combinação com codificação unicode.

  • gh-95782: Corrige io.BufferedReader.tell(), io.BufferedReader.seek(), _pyio.BufferedReader.tell(), io.BufferedRandom.tell(), io.BufferedRandom.seek() e _pyio.BufferedRandom.tell() sendo capazes de retornar deslocamentos negativos.

  • gh-96310: Corrige um traceback em argparse quando todas as opções em um grupo mutuamente exclusivo são suprimidas.

  • gh-93205: Corrige um bug em logging.handlers.TimedRotatingFileHandler onde várias instâncias de manipulador rotativo apontando para arquivos com o mesmo nome, mas extensões diferentes, entrariam em conflito e não excluiriam os arquivos corretos.

  • bpo-31116: Adiciona codificação Z85 a base64.

  • bpo-44865: Adiciona chamada ausente para função de localização em argparse.

  • bpo-43952: Corrige multiprocessing.connection.Listener.accept() para aceitar bytes vazios como authkey. Não aceitar bytes vazios como chave faz com que ele trave indefinidamente.

  • bpo-42125: linecache: obtém nome do módulo de __spec__ se disponível. Isso permite obter código-fonte para o módulo __main__ quando um carregador personalizado é usado.

  • bpo-41122: Não passar argumentos corretamente para functools.singledispatchmethod() agora levanta um TypeError em vez de atingir um índice fora dos limites internamente.

  • bpo-40818: O asyncio REPL agora executa sys.__interactivehook__ na inicialização. A implementação padrão de sys.__interactivehook__ fornece preenchimento automático para o asyncio REPL. O patch é uma contribuição por Rémi Lapeyre.

  • bpo-33775: Adiciona o texto de ajuda ‘default’ e ‘version’ para localização no argparse.

Documentação

Testes

  • gh-71052: Adiciona exclusões de teste para dar suporte à execução do conjunto de testes no Android.

  • gh-71052: Habilita test_concurrent_futures em plataformas que oferecem suporte a threads, mas não multiprocessamento.

  • gh-115796: Faz com que ‘_testinternalcapi.assemble_code_object’ construa a tabela de exceções para o objeto de código.

  • gh-115720: Testes de vazamento (-R, --huntrleaks) agora mostram um resumo do número de vazamentos encontrados em cada iteração.

  • gh-115122: Adiciona a opção --bisect ao executor de teste regrtest: execute testes com falha com test.bisect_cmd para identificar testes com falha. Patch por Victor Stinner.

  • gh-115596: Corrige ProgramPriorityTests em test_os alterando permanentemente a prioridade do processo.

  • gh-115556: No Windows, vírgulas passadas em argumentos para Tools\buildbot\test.bat e PCbuild\\rt.bat agora são manipuladas corretamente.

  • gh-115420: Corrige tradução de alvos de manipuladores de exceção por _testinternalcapi.optimize_cfg.

  • gh-115376: Corrige falha de segmentação em _testinternalcapi.compiler_codegen em entrada incorreta.

Construção

  • gh-116313: Faz com que construções WASI funcionem no wasmtime 18 com primitivos WASI 0.2/preview2.

  • gh-71052: Altera sys.platform do Android de "linux" para "android".

  • gh-116117: Faz backport da PR #42 da libb2 para corrigir a compilação do CPython no Windows de 32 bits com clang-cl.

  • gh-71052: Corrige vários problemas de construção do Android

  • gh-114099: Um projeto de testbed foi adicionado para executar o conjunto de testes no iOS.

  • gh-115350: Corrige o módulo de construção ctypes com -DWIN32_LEAN_AND_MEAN definido

  • gh-111225: Vincula módulos de extensão ao libpython no Android.

  • gh-115737: O nome de instalação do libPython agora está definido corretamente para compilações macOS sem framework.

  • gh-114099: Os alvos do Makefile foram adicionados para oferecer suporte à compilação de uma construção de framework compatível com iOS.

Windows

  • gh-116012: Garante que o valor de GetLastError() seja preservado em todas as operações com a GIL.

  • gh-115582: Construir extensões destinadas a construções com threads livres do CPython agora exigem a compilação manual com /DPy_GIL_DISABLED ao usar uma instalação regular. Espera-se que isso mude em versões futuras.

  • gh-115554: O instalador agora tem regras mais rígidas sobre a atualização do Gerenciador de instalação do Python. Em geral, a maioria dos usuários tem apenas um único iniciador instalado e não verá nenhuma diferença. Quando vários iniciadores foram instalados, a opção de instalar o iniciador é desabilitada até que todos, exceto um, tenham sido removidos. O downgrade do iniciador (que nunca foi permitido) agora é mais obviamente bloqueado.

  • gh-115543: Gerenciador de instalação do Python agora pode detectar o Python 3.13 quando instalado da Microsoft Store e instalará o Python 3.12 por padrão quando PYLAUNCHER_ALLOW_INSTALL estiver definido.

macOS

  • gh-116145: Atualiza instalador do macOS para Tcl/Tk 8.6.14.

IDLE

  • gh-88516: No macOS, mostra um ícone de proxy na barra de título das janelas do editor para corresponder ao comportamento da plataforma.

Ferramentas/Demos

  • gh-100176: Remove Tools/{io,cc,string}bench desatualizado

  • bpo-45101: Adiciona consistência na mensagem de uso de E/S entre 2 versões do python-config.

API C

  • gh-114626: Adiciona novamente o nome _PyCFunctionFastWithKeywords, removido no Python 3.13 alpha 4 por engano. Manter o antigo nome privado _PyCFunctionFastWithKeywords (Python 3.7) como um apelido para o novo nome público PyCFunctionFastWithKeywords (Python 3.13a4). Patch por Victor Stinner.

  • gh-111418: Adiciona as macros C PyHASH_MODULUS, PyHASH_BITS, PyHASH_INF e PyHASH_IMAG. Patch por Sergey B Kirpichev.

Python 3.13.0 alpha 4

Data de lançamento: 2024-02-15

Segurança

Núcleo e embutidos

  • gh-112087: Para um iterador reverso vazio for, lista será reduzida para reversed(). Patch por Donghee Na

  • gh-114570: Adiciona exceção PythonFinalizationError. Esta exceção derivada de RuntimeError é levantada quando uma operação é bloqueada durante a finalização do Python. Patch por Victor Stinner.

  • gh-114695: Adiciona sys._clear_internal_caches(), que limpa todos os caches internos relacionados ao desempenho (e descontinua a função menos geral sys._clear_type_cache()).

  • gh-114828: Corrige travamentos de compilação em exemplos de código incomuns usando super() dentro de uma compreensão em um corpo de classe.

  • gh-112069: Adapta os métodos set e frozenset para Argument Clinic.

  • gh-115011: Setters para membros com um tipo inteiro sem sinal agora oferecem suporte ao mesmo intervalo de valores válidos para objetos que têm um método __index__() como para int.

  • gh-114887: Alterada a validação do tipo de soquete em create_datagram_endpoint() para aceitar todos os soquetes não-stream. Isso corrige uma regressão na compatibilidade com soquetes brutos.

  • gh-114944: Corrige uma corrida entre PyParkingLot_Park e _PyParkingLot_UnparkAll.

  • gh-113462: Limita o número de versões que uma única classe pode usar. Impede que algumas classes rebeldes usem todos os números de versão.

  • gh-76763: A função embutido chr() agora sempre levanta ValueError para valores fora do intervalo válido. Anteriormente, levantava OverflowError para valores muito grandes ou pequenos.

  • gh-114806: Não especializa mais chamadas para classes, se essas classes tiverem metaclasses. Corrige bug onde o método __call__ da metaclasse não estava sendo chamado.

  • gh-107944: Melhora mensagem de erro para chamadas de função com argumentos nomeados inválidos via getargs

  • gh-112529: A construção com threads livres não aloca mais espaço para a estrutura PyGC_Head em objetos que oferecem suporte a coleta de lixo cíclica. Vários outros campos e estruturas de dados são usados como substituições, incluindo ob_gc_bits, ob_tid e estruturas de dados internas mimalloc.

  • gh-114456: Reduz o limite de recursão em uma construção de depuração do WASI.

  • gh-114083: O compilador aplica o dobramento de LOAD_CONST com a instrução a seguir em uma passagem separada antes de outras otimizações. Isso permite o jump threading em certas circunstâncias.

  • gh-114388: Corrige um RuntimeWarning emitido ao atribuir um valor inteiro que não é uma instância de int a um atributo que corresponde a um membro struct C de type T_UINT e T_ULONG. Corrige um RuntimeWarning duplo emitido ao atribuir um valor inteiro negativo a um atributo que corresponde a um membro struct C do tipo T_UINT.

  • gh-114265: O compilador propaga números de linha antes da otimização, levando a mais oportunidades de otimização e removendo a necessidade do hack guarantee_lineno_for_exits.

  • gh-112529: A construção com threads livres agora tem sua própria implementação de GC segura para thread que usa mimalloc para encontrar objetos rastreados por GC. Não é geracional, diferente da implementação GC existente.

  • gh-114050: Corrige falha de segmentação causada por uma string de formato incorreta na exceção TypeError quando mais de dois argumentos são passados para int.

  • gh-112354: A instrução END_FOR agora exibe apenas um valor. Isso é para oferecer melhor suporte a saídas laterais em laços.

  • gh-113884: Torna queue.SimpleQueue segura para thread quando a GIL estiver desabilitada.

  • gh-114058: Implementa as bases do eliminador de redundância de Nível 2.

  • gh-113939: frame.clear(): Limpa frame.f_locals também, e não apenas os locals rápidos. Isso é relevante quando frame.f_locals foi acessado, o que também conteria referências a todos os locais.

  • gh-112050: Converte collections.deque para usar Argument Clinic.

  • gh-112050: Torna os métodos em collections.deque seguros para thread quando a GIL estiver desabilitada.

  • gh-113464: Adiciona uma opção (--enable-experimental-jit para construções baseadas em configure ou --experimental-jit para construções baseadas em PCbuild) para construir um compilador experimental just-in-time, baseado em copy-and-patch

  • gh-113055: Torna interp->obmalloc um ponteiro. Para interpretadores que compartilham estado com o interpretador principal, isso aponta para a mesma estrutura de memória estática. Para interpretadores com seu próprio estado obmalloc, ele é alocado em heap. Adiciona free_obmalloc_arenas() que liberará as arenas obmalloc e as estruturas de árvore radix para interpretadores com seu próprio estado obmalloc.

  • gh-55664: Adiciona um aviso ao criar type usando um dicionário de espaço de nomes com chaves não string. Patch por Daniel Urban e Furkan Onder.

  • gh-104530: Usa variáveis de condição nativas do Win32.

Biblioteca

  • gh-115392: Corrige um bug em doctest onde números de linha incorretos seriam relatados para funções decoradas.

  • gh-114563: Corrige vários bugs de format() ao usar a implementação C de Decimal: * vazamento de memória em alguns casos raros ao usar a opção de formato z (coagir negativo 0) * saída incorreta ao aplicar a opção de formato z ao tipo F (ponto fixo com NAN maiúsculo / INF) * saída incorreta ao aplicar a opção de formato # (formato alternativo)

  • gh-102840: Corrige traceback confuso quando as operações floordiv, mod ou divmod acontecem entre instâncias de fractions.Fraction e complex.

  • gh-115165: A maioria das exceções agora são ignoradas ao tentar definir o atributo __orig_class__ em objetos retornados ao chamar apelidos genéricos typing (incluindo aliases genéricos criados usando typing.Annotated). Anteriormente, apenas AttributeError era ignorada. Patch por Dave Shawley.

  • gh-112903: Corrige erros de “issubclass() arg 1 must be a class” em certos casos de herança múltipla com aliases genéricos (regressão nas primeiras versões alfa 3.13).

  • gh-115133: Corrige testes para XMLPullParser com Expat 2.6.0.

  • gh-115059: io.BufferedRandom.read1() agora limpa o buffer de gravação subjacente.

  • gh-79382: ** no final não permite mais corresponder arquivos e caminhos não existentes em glob() recursivo.

  • gh-67837: Evita condições de corrida na criação de diretórios durante a extração simultânea em tarfile e zipfile.

  • gh-115060: Acelera pathlib.Path.glob() removendo a correspondência de regex redundante.

  • gh-97928: Reverte parcialmente o comportamento de tkinter.Text.count(). Por padrão, ele preserva o comportamento de versões mais antigas do Python, exceto que definir wantobjects como 0 não tem mais efeito. Adiciona um novo parâmetro return_ints: especificar return_ints=True faz com que Text.count() sempre retorna a contagem única como um inteiro em vez de uma tupla de 1 elemento ou None.

  • gh-114628: Quando csv.Error é levantada ao manipular TypeError, não exibir o traceback de TypeError.

  • gh-85984: Adicionado _POSIX_VDISABLE de <unistd.h> de C para termios.

  • gh-114965: Atualiza pip empacotado para 24.0

  • gh-114959: tarfile não ignora mais erros ao tentar extrair um diretório em cima de um arquivo.

  • gh-114894: Adiciona array.array.clear().

  • gh-114071: Suporte a subclasses de tupla usando auto() para valor de membro enum.

  • gh-109475: Corrige suporte ao valor de opção explícito “–” em argparse (por exemplo, --option=--).

  • gh-49766: Corrige comparação date-datetime. Agora, os métodos de comparação especiais como __eq__ e __lt__ retornam NotImplemented se um dos comparandos for date e o outro for datetime em vez de ignorar a parte do tempo e o fuso horário ou retornar forçadamente “não igual” ou levantar TypeError. Ele torna a comparação das subclasses date e datetime mais simétrica e permite alterar o comportamento padrão substituindo os métodos de comparação especiais em subclasses.

  • gh-110190: Corrige estruturas ctypes com vetor na plataforma Windows ARM64 definindo MAX_STRUCT_SIZE como 32 em stgdict. Patch por Diego Russo

  • gh-114678: Garante que o aviso de descontinuação para o especificador ‘N’ no formato Decimal não seja levantada para casos em que ‘N’ aparece em outros lugares no especificador de formato. Baseado no patch por Stefan Krah.

  • gh-70303: Retorna arquivos e diretórios de pathlib.Path.glob() se um padrão termina com “**”. Anteriormente, apenas diretórios eram retornados.

  • gh-109653: Melhora o tempo de importação de importlib.metadata e email.utils.

  • gh-113280: Corrige um vazamento de soquete aberto em casos raros quando ocorria um erro na criação de ssl.SSLSocket.

  • gh-77749: email.policy.EmailPolicy.fold() agora sempre codifica caracteres não ASCII em cabeçalhos se utf8 for falso.

  • gh-83383: A sincronização do banco de dados dbm.dumb agora é no-op se não houver modificação desde a abertura ou última sincronização. O arquivo de diretório para um banco de dados dbm.dumb vazio recém-criado agora é criado imediatamente após a abertura, em vez de adiar isso até a sincronização ou o fechamento.

  • gh-91602: Adiciona o parâmetro somente-nomeado filter a sqlite3.Connection.iterdump() para filtrar objetos de banco de dados para despejar. Patch por Mariusz Felisiak.

  • gh-112451: Proíbe criar subclasse de Python puro datetime.timezone. Isso é consistente com a implementação da extensão C. Patch por Mariusz Felisiak.

  • gh-69893: Adiciona o método close() para o iterador retornado por xml.etree.ElementTree.iterparse().

  • gh-109653: Reduz o tempo de importação do módulo threading em ~50%. Patch por Daniel Hollas.

  • gh-114492: Torna o resultado de termios.tcgetattr() reproduzível no Alpine Linux. Anteriormente, ele poderia deixar um lixo aleatório em alguns campos.

  • gh-114315: Torna threading.Lock uma classe real, não uma função de fábrica. Adiciona __new__ ao tipo _thread.lock.

  • gh-100414: Adiciona dbm.sqlite3 como um backend para dbm, e torna-o o novo backend padrão dbm. Patch por Raymond Hettinger e Erlend E. Aasland.

  • gh-113267: Reverte alterações em gh-106584 que tornavam as chamadas dos métodos TestResult startTest() e stopTest() desbalanceadas.

  • gh-75128: Ignora uma OSError em asyncio.BaseEventLoop.create_server() quando o IPv6 estiver disponível, mas a interface não puder realmente suportá-lo.

  • gh-114423: As entradas _DummyThread em threading._active agora são removidas automaticamente quando o thread relacionado morre.

  • gh-114257: Descarta o erro FileNotFound em ctypes.util.find_library() e retorna apenas None no Linux.

  • gh-114321: Expõe mais constantes específicas da plataforma no módulo fcntl no Linux, macOS, FreeBSD e NetBSD.

  • gh-114328: A tty.setcbreak() e a nova tty.cfmakecbreak() não limpam mais o sinalizador ICRLF de entrada do terminal. Isso corrige uma regressão introduzida na 3.12 que não correspondia mais a como os sistemas operacionais definem o modo cbreak em suas páginas de manual stty(1).

  • gh-114281: Remove dicas de tipo de Lib/asyncio/staggered.py. As anotações no projeto typeshed devem ser usadas em vez disso.

  • gh-101438: Evite o ciclo de referência em ElementTree.iterparse. O iterador retornado por ElementTree.iterparse pode manter um descritor de arquivo. O ciclo de referência impedia a limpeza rápida do descritor de arquivo se o iterador retornado não estivesse esgotado.

  • gh-114198: A assinatura para o método __replace__ em dataclasses agora tem o primeiro argumento chamado self, em vez de obj.

  • gh-104522: OSError levantada ao executar um subprocesso agora tem apenas o atributo filename definido como cwd se o erro foi causado por uma tentativa malsucedida de alterar o diretório atual.

  • gh-114149: Enum: manipula corretamente subclasses de tuplas em __new__ personalizado.

  • gh-83648: Suporta descontinuação de opções, argumentos posicionais e subcomandos em argparse.

  • gh-114087: Acelera dataclasses.asdict em até 1,35x.

  • gh-109534: Corrige um vazamento de referência em asyncio.selector_events.BaseSelectorEventLoop quando negociações SSL falham. Patch foi contribuição de Jamie Phan.

  • gh-79634: Aceita objetos caminho ou similares como padrões em pathlib.Path.glob() e rglob().

  • gh-112202: Garante que uma chamada asyncio.Condition.notify() não seja perdida se a Task despertada for cancelada simultaneamente ou encontrar qualquer outro erro.

  • gh-113951: Corrige o comportamento dos métodos tag_unbind() das classes tkinter.Text e tkinter.Canvas com três argumentos. Anteriormente, widget.tag_unbind(tag, sequence, funcid) destruía a vinculação atual para sequence, deixando sequence desvinculado, e excluía o comando funcid. Agora, ele remove apenas funcid da vinculação para sequence, mantendo outros comandos, e exclui o comando funcid. Ele deixa sequence desvinculado somente se funcid foi o último comando vinculado.

  • gh-97959: Corrige métodos de classe de renderização, métodos vinculados, métodos e apelidos de função em pydoc. Métodos de classe não têm mais a nota “método de instância builtins.type”. Notas correspondentes agora são adicionadas para métodos de classe e não vinculados. Apelidos de método e função agora têm referências ao módulo ou à classe onde a origem foi definida se for diferente da atual. Métodos vinculados agora são listados na seção de métodos estáticos. Métodos de classes internas agora são suportados, bem como métodos de classes Python.

  • gh-113796: Adiciona mais verificações de validação no construtor csv.Dialect. ValueError agora é levantada se o mesmo caractere for usado em funções diferentes.

  • gh-113732: Corrige suporte de QUOTE_NOTNULL e QUOTE_STRINGS em csv.reader().

  • gh-113225: Acelera pathlib.Path.walk() usando os.DirEntry.path onde possível.

  • gh-89039: Quando o método replace() é chamado em uma subclasse de datetime, date ou time, chamar corretamente o construtor derivado. Anteriormente, apenas o construtor da classe base era chamado.

    Além disso, certifica-se de passar valores de fold diferentes de zero ao criar subclasses em vários métodos. Anteriormente, fold era ignorado silenciosamente.

  • gh-112919: Aceleração de datetime.datetime.replace(), datetime.date.replace() e datetime.time.replace().

  • gh-59013: Define o ponto de interrupção na primeira linha executável da função, em vez da linha de definição da função quando o usuário faz break func usando pdb

  • gh-112343: Melhora o tratamento de variáveis de conveniência pdb para evitar a substituição de conteúdo de string.

  • gh-112240: Adiciona opção à CLI do módulo de calendar para especificar o dia da semana para começar cada semana. Patch por Steven Ward.

  • gh-111741: Reconhece image/webp como um formato padrão no módulo mimetypes.

  • gh-43457: Corrige o método do widget tkinter wm_attributes(). Agora ele aceita o nome do atributo sem o prefixo menos para obter atributos de janela e permite especificar atributos e valores para ser definido como argumentos nomeados. Adiciona um novo argumento nomeado opcional return_python_dict: chamar w.wm_attributes(return_python_dict=True) retorna os atributos como um dict em vez de uma tupla. Chamar w.wm_attributes() agora retorna uma tupla em vez de uma string se wantobjects foi definido como 0.

  • gh-82626: Muitas funções agora emitem um aviso se um valor booleano for passado como um argumento de descritor de arquivo.

  • gh-111051: Adicionada verificação para modificação de arquivo durante a depuração com pdb

  • gh-110345: Mostra o patchlevel Tcl/Tk (em vez da versão) em tkinter._test().

  • gh-38807: Corrige a condição de corrida em trace. Em vez de verificar se um diretório existe e criá-lo, chame diretamente os.makedirs() com o kwarg exist_ok=True.

  • gh-75705: Define o envelope unixfrom em mailbox.mbox e mailbox.MMDF.

  • gh-106233: Corrige o stacklevel em InvalidTZPathWarning durante a importação do módulo zoneinfo.

  • gh-105102: Permita que ctypes.Union seja aninhado em ctypes.Structure quando o endianness do sistema for o oposto das classes.

  • gh-104282: Corrige a desreferência de ponteiro nulo em lzma._decode_filter_properties() devido ao tratamento impróprio de filtros BCJ com propriedades de comprimento zero. Patch por Radislav Chugunov.

  • gh-96471: Adiciona terminação queue.Queue com shutdown().

  • gh-101599: Altera a formatação de opções de sinalizador argparse para remover redundância.

  • gh-85984: Adiciona funções pseudoterminais POSIX os.posix_openpt(), os.grantpt(), os.unlockpt() e os.ptsname().

  • gh-102512: Quando os.fork() é chamado de um thread estrangeiro (também conhecido como _DummyThread), o tipo do thread em um processo filho é alterado para _MainThread. Também alterou seu nome e status como daemon, agora pode ser unido.

  • gh-88569: Adiciona os.path.isreserved(), que identifica nomes de caminho reservados como “NUL”, “AUX” e “CON”. Esta função está disponível somente no Windows.

    Deprecate pathlib.PurePath.is_reserved().

  • bpo-38364: As funções inspect isgeneratorfunction, iscoroutinefunction, isasyncgenfunction agora oferecem suporte a funções encapsuladas functools.partialmethod da mesma forma que oferecem suporte a functools.partial.

Documentação

  • gh-115233: Corrige um exemplo para LoggerAdapter no Logging Cookbook.

  • gh-114123: Move a docstring do módulo csv para o módulo csv em vez de reexportá-la do módulo interno _csv e remove __doc__ de csv.__all__.

    Move csv.__version__ para o módulo csv em vez de reexportá-lo do módulo interno _csv e remove __version__ de csv.__all__.

Testes

  • gh-114099: Adicionadas exclusões de teste necessárias para executar o conjunto de testes no iOS.

  • gh-105089: Corrige o teste test.test_zipfile.test_core.TestWithDirectory.test_create_directory_with_write no AIX fazendo um AND bit a bit de 0xFFFF no modo , para que ele fique sincronizado com zinfo.external_attr

Construção

  • gh-115167: Evita incluir vcruntime140_threads.dll ao Python ao construir com o Visual Studio 2022 versão 17.8.

  • gh-113632: Promove o WASI para uma plataforma de nível 2 e remove o Emscripten do nível 3 em configure.ac.

  • gh-114099: configure e Makefile foram refatorados para acomodar construções de framework em plataformas Apple diferentes do macOS.

  • gh-114875: Adiciona getgrent() como um pré-requisito para construir o módulo grp.

Windows

  • gh-115049: Corrige a falha do iniciador py.exe quando executado como usuários sem perfis de usuário.

  • gh-115009: Atualize o instalador do Windows para usar o SQLite 3.45.1.

  • gh-109991: Atualize a construção do Windows para usar o OpenSSL 3.0.13.

  • gh-111239: Atualiza as construções do Windows para usar o zlib v1.3.1.

  • gh-100107: O iniciador py.exe não tentará mais executar o redirecionador da Microsoft Store ao iniciar um script contendo um shebang /usr/bin/env

  • gh-112984: Adiciona binários de threads livres ao instalador do Windows como um componente opcional.

  • gh-89240: Permite que multiprocessing crie pools com mais de 62 processos.

macOS

  • gh-115009: Atualiza o instalador do macOS para usar o SQLite 3.45.1.

  • gh-109991: Atualiza o instalador do macOS para usar OpenSSL 3.0.13.

  • gh-114490: Adiciona suporte de ligação Mach-O para platform.architecture().

  • gh-87804: No macOS, o resultado de os.statvfs e os.fstatvfs agora relata corretamente o tamanho de discos muito grandes, em versões anteriores o número relatado de blocos estava errado para discos com pelo menos 2**32 blocos.

IDLE

  • gh-96905: No código de idlelib, para de redefinir os tipos embutidos ‘dict’ e ‘object’.

  • gh-103820: Revisa as ligações do IDLE para que os eventos do botão do mouse 4/5 em sistemas de janelas não X11 (por exemplo, Win32 e Aqua) não sejam confundidos com rolagem.

Ferramentas/Demos

  • gh-113516: Não define LDSHARED ao construir para WASI.

  • gh-109991: Atualiza fluxos de trabalho do GitHub CI para usar OpenSSL 3.0.13 e multissltests para usar 1.1.1w, 3.0.13, 3.1.5 e 3.2.1.

  • gh-115015: Corrige um bug no Argument Clinic que gerava código incorreto para métodos sem parâmetros que usam a convenção de chamada METH_METHOD | METH_FASTCALL | METH_KEYWORDS. Apenas a contagem de parâmetros posicionais foi verificada; qualquer argumento nomeado passado seria aceito silenciosamente.

API C

Python 3.13.0 alpha 3

Data de lançamento: 2024-01-17

Segurança

  • gh-113659: Pula arquivos .pth com nomes começando com um ponto ou atributo de arquivo oculto.

  • gh-112302: Criado um documento de lista de materiais de software e ferramentas para rastrear dependências.

Núcleo e embutidos

  • gh-107901: O compilador duplica blocos básicos que têm uma verificação de quebra de avaliação, nenhum número de linha e vários predecessores.

  • gh-107901: Um salto que deixa um manipulador de exceção de volta ao código normal não verifica mais o quebra de avaliação.

  • gh-113655: Define o limite de recursão C para 4000 no Windows e 10000 no Linux/OSX. Isso parece estar perto do ponto ideal para manter a segurança, mas não comprometer a retrocompatibilidade.

  • gh-113710: Adiciona efeitos de pilha digitados ao DSL do interpretador, junto com várias anotações de instruções.

  • gh-77046: No Windows, os descritores de arquivo que envolvem identificadores do Windows agora são criados não herdáveis por padrão (PEP 446). Patch por Zackery Spytz e Victor Stinner.

  • gh-113853: Garante que todos os executores progridam. Isso garante que a execução de nível 2 sempre progrida.

  • gh-113753: Corrige um problema em que o finalizador de objetos PyAsyncGenASend pode não ser chamado se eles forem alocados de uma lista livre.

  • gh-107901: Compilador alterado para que saltos sintéticos que não estejam no final do laço não verifiquem mais o disjuntor de avaliação.

  • gh-113703: Corrige uma regressão no módulo codeop que estava fazendo com que ele identificasse incorretamente f-strings incompletas. Patch por Pablo Galindo

  • gh-89811: Verifica se há uma tp_version_tag válida antes de executar especializações de bytecode que dependem desse valor ser utilizável.

  • gh-111488: Mensagem de erro alterada em caso de nenhuma palavra reservada ‘in’ após ‘for’ em compreensões de lista

  • gh-113657: Corrige um problema que fazia com que atualizações importantes de ponteiros de instruções fossem otimizadas fora dos rastreamentos de nível dois.

  • gh-113603: Corrige um bug em que um NOP redundante não é removido, causando falha em uma asserção no compilador no modo de depuração.

  • gh-113602: Corrige um erro que fazia com que o analisador sintático tentasse sobrescrever erros existentes e travasse no processo. Patch por Pablo Galindo

  • gh-113486: Não emite mais eventos PY_UNWIND espúrios para chamadas otimizadas para classes.

  • gh-113297: Corrige falha de segmentação no compilador na instrução with com 19 gerenciadores de contexto.

  • gh-113212: Melhora as mensagens de erro de super.

  • gh-111375: Usa somente NULL na pilha de exceções para indicar que uma exceção foi tratada. Patch por Carey Metcalfe.

  • gh-112215: Aumenta o limite de recursão C por um fator de 3 para compilações não depuradas, exceto para plataformas webassembly e s390 que não foram alteradas. Isso atenua algumas regressões no 3.12 com recursão profunda misturando código interno (C) e Python.

  • gh-113054: Corrigido bug onde um NOP redundante não é removido, causando falha em uma asserção no compilador no modo de depuração.

  • gh-106905: Usa o estado por analisador sintático AST em vez do estado global para rastrear a profundidade da recursão dentro do analisador sintático AST para evitar uma possível condição de corrida devido à análise simultânea.

    O problema apareceu principalmente na versão 3.11 por usuários multithread de ast.parse(). Na versão 3.12, uma alteração em quando a coleta de lixo pode ser acionada impediu que a condição de corrida ocorresse.

  • gh-108866: Altera a API e o contrato de _PyExecutorObject para retornar o ponteiro next_instr, em vez do quadro, e para sempre executar pelo menos uma instrução.

  • gh-90350: Otimiza as funções embutidas min() e max().

  • gh-112943: Calcula corretamente os deslocamentos de coluna final para tokens multilinha no módulo tokenize. Patch por Pablo Galindo

  • gh-112125: Corrige None.__ne__(None) retornando NotImplemented em vez de False.

  • gh-74616: input() agora levanta uma ValueError quando emitido no terminal se o prompt contiver caracteres nulos incorporados em vez de truncá-lo silenciosamente.

  • gh-112716: Corrige SystemError na instrução import e nos métodos __reduce__() de tipos embutidos quando __builtins__ não é um dict.

  • gh-112730: Usa cor para destacar locais de erro em tracebacks. Patch por Pablo Galindo

  • gh-112625: Corrige um bug em que um objeto bytearray poderia ser limpo durante a iteração sobre um argumento no método bytearray.join() que poderia resultar na leitura de memória após ser liberado.

  • gh-112660: Não limpa erros inesperados durante mensagens de erro de formatação para ImportError e AttributeError para módulos.

  • gh-105967: Solução alternativa para um bug na biblioteca zlib da plataforma macOS da Apple, em que zlib.crc32() e binascii.crc32() poderiam produzir resultados incorretos em entradas de vários gigabytes. Incluindo ao usar zipfile em zips contendo dados grandes.

  • gh-95754: Fornece uma mensagem de erro melhor ao acessar atributos inválidos em módulos parcialmente inicializados. A origem do módulo que está sendo acessado agora está incluída na mensagem para ajudar com o problema comum de sombreamento de outros módulos.

  • gh-112217: Adiciona verificação para o tipo de __cause__ retornado da chamada do tipo T em raise from T.

  • gh-111058: Altera coro.cr_frame/gen.gi_frame para retornar None após a corrotina/gerador ter sido fechado. Isso corrige um bug em que getcoroutinestate() e getgeneratorstate() retornam o estado errado para uma corrotina/gerador fechado.

  • gh-112388: Corrige um erro que estava fazendo o analisador tentar sobrescrever erros do tokenizador. Patch por pablo Galindo

  • gh-112387: Corrige posições de erro para strings decodificadas com erros de análise léxica reversa. Patch por Pablo Galindo

  • gh-99606: Torna o código gerado para uma f-string vazia idêntico ao código de uma string normal vazia.

  • gh-112367: Evita comportamento indefinido ao usar os trampolins do perf não liberando as arenas de código até o desligamento. Patch por Pablo Galindo

  • gh-112320: O tradutor de nível 2 agora rastreia o nível de confiança para permanecer “no rastreamento” (ou seja, não sair de volta para o interpretador de nível 1) para instruções de ramificação com base no número de bits definidos no “contador” de ramificação. A tradução de rastreamento termina quando a confiança cai abaixo de 1/3.

  • gh-109598: PyComplex_RealAsDouble()/PyComplex_ImagAsDouble() agora tenta converter um objeto para uma instância complex usando seu método __complex__() antes de retornar ao método __float__(). Patch por Sergey B Kirpichev.

  • gh-94606: Corrige UnicodeEncodeError quando email.message.get_payload() lê uma mensagem com um caractere substituto Unicode e o conteúdo da mensagem não está bem formado para codificação de escape substituto. Patch por Sidney Markowitz.

  • bpo-21861: Usa o nome de classe real do objeto em _io.FileIO.__repr__(), _io._WindowsConsoleIO() e _io.TextIOWrapper.__repr__(), para tornar esses métodos amigáveis à subclasse.

  • bpo-45369: Remove soluções alternativas do LibreSSL conforme a PEP 644.

  • bpo-34392: Adicionada sys._is_interned().

Biblioteca

  • gh-114077: Corrige possível OverflowError em socket.socket.sendfile() ao passar count maior que 2 GiB em plataforma de 32 bits.

  • gh-111803: plistlib agora oferece suporte ao carregamento de listas aninhadas mais profundamente em formato binário.

  • gh-114014: Corrige um bug em fractions.Fraction onde uma string inválida usando d na parte decimais cria um erro diferente comparado a outras letras/caracteres inválidos. Patch por Jeremiah Gabriel Pascual.

  • gh-108364: sqlite3.Connection.iterdump() agora garante que o suporte a chave estrangeira seja desabilitado antes de despejar o esquema do banco de dados, se houver qualquer violação de chave estrangeira. Patch por Erlend E. Aasland e Mariusz Felisiak.

  • gh-113971: O atributo ._compresslevel protegido anteriormente por zipfile.ZipInfo foi tornado público como .compress_level com o antigo nome _compresslevel permanecendo disponível como uma propriedade para manter a compatibilidade.

  • gh-113877: Corrige o método winfo_pathname() do tkinter no Windows de 64 bits.

  • gh-113868: Adicionados mmap.MAP_NORESERVE, mmap.MAP_NOEXTEND, mmap.MAP_HASSEMAPHORE, mmap.MAP_NOCACHE, mmap.MAP_JIT, mmap.MAP_RESILIENT_CODESIGN, mmap.MAP_RESILIENT_MEDIA, mmap.MAP_32BIT, mmap.MAP_TRANSLATED_ALLOW_EXECUTE, mmap.MAP_UNIX03 e mmap.MAP_TPRO. Todos eles são sinalizadores mmap(2) no macOS.

  • gh-113848: Os gerenciadores de contexto asyncio.TaskGroup() e asyncio.timeout() agora manipulam as subclasses CancelledError, bem como CancelledError exato.

  • gh-113661: unittest runner: Não sai com 5 se os testes foram ignorados. A intenção de sair com 5 era detectar problemas em que o conjunto de testes não foi descoberto. Se pulamos os testes, ele foi descoberto corretamente.

  • gh-96037: Insere TimeoutError no contexto da exceção que foi levantada durante a saída de um bloco asyncio.timeout() expirado.

  • gh-113781: Silencia AttributeError não levantável quando avisos são emitidos durante a finalização do Python.

  • gh-113238: Adiciona Anchor a importlib.resources (para que o código esteja em conformidade com a documentação)

  • gh-111693: asyncio.Condition.wait() agora levanta novamente a mesma instância CancelledError que pode ter causado sua interrupção. Corrigida a condição de corrida em asyncio.Semaphore.acquire() quando interrompido com uma CancelledError.

  • gh-113791: Adiciona CLOCK_MONOTONIC_RAW_APPROX e CLOCK_UPTIME_RAW_APPROX a time no macOS. Esses são relógios disponíveis no macOS 10.12 ou posterior.

  • gh-112932: Restaura a capacidade de zipfile de extractall de arquivos zip com uma entrada de diretório “/” neles, como é comumente adicionado a zips por alguns exportadores de dados de wiki ou rastreadores de bugs.

  • gh-113568: Levanta avisos de descontinuação de pathlib.PurePath e não de sua classe base privada PurePathBase.

  • gh-113594: Corrige UnicodeEncodeError em email ao redobrar linhas que contêm parte codificada de 8 bits desconhecida seguida por parte codificada de 8 bits não desconhecida.

  • gh-113538: Em asyncio.StreamReaderProtocol.connection_made(), há um retorno de chamada que registra um erro se a tarefa que envolve o “retorno de chamada de conectado” falhar. Este retorno de chamada falharia se a tarefa fosse cancelada. Evite isso verificando se a tarefa foi cancelada primeiro. Se sim, feche o transporte, mas não registre um erro.

  • gh-113626: Adiciona suporte para o argumento allow_code no módulo marshal. Passar allow_code=False previne a serialização e desserialização de objetos de código, o que é incompatível entre versões do Python.

  • gh-85567: Corrige avisos de recursos para arquivos não fechados nas interfaces de linha de comando pickle e pickletools.

  • gh-113537: Suporte a cargas de str em plistlib.loads().

  • gh-89850: Adiciona implementações padrão dos métodos pickle.Pickler.persistent_id() e pickle.Unpickler.persistent_load() na implementação C. Chamar super().persistent_id() e super().persistent_load() em subclasses da implementação C das classes pickle.Pickler e pickle.Unpickler não causa mais recursão infinita.

  • gh-113569: Indica se não houve chamadas reais na falha do unittest assert_has_calls().

  • gh-101225: Aumenta o backlog para objetos multiprocessing.connection.Listener criados por multiprocessing.manager e multiprocessing.resource_sharer para reduzir significativamente o risco de obter um erro de conexão recusada ao criar um multiprocessing.connection.Connection para eles.

  • gh-113568: Levanta eventos de auditoria de pathlib.Path e não de sua classe base privada PathBase.

  • gh-113543: Garante que webbrowser.MacOSXOSAScript envie o evento de auditoria webbrowser.open.

  • gh-113028: Quando uma segunda referência a uma string aparece na entrada para pickle, e a implementação Python está em uso, temos a garantia de que uma única cópia é decapada e um único objeto é compartilhado quando recarregado. Anteriormente, no protocolo 0, quando uma string continha certos caracteres (por exemplo, nova linha), isso resultava em objetos duplicados.

  • gh-113421: Corrige o logger de multiprocessamento para %(filename)s.

  • gh-111784: Corrige falhas de segmentação no módulo _elementtree. Corrige a primeira falha de segmentação durante a desalocação de instâncias _elementtree.XMLParser mantendo uma referência forte ao módulo pyexpat no estado do módulo para o tempo de vida da cápsula. Corrige a segunda falha de segmentação que acontece no mesmo processo de desalocação mantendo uma referência forte ao módulo _elementtree na estrutura XMLParser para o tempo de vida do módulo _elementtree.

  • gh-113407: Corrige a importação de unittest.mock quando o CPython é construído sem docstrings.

  • gh-113320: Corrige uma regressão no Python 3.12 onde classes Protocol que não foram marcadas como runtime-checkable seriam introspectadas desnecessariamente, potencialmente causando exceções se o protocolo tivesse membros problemáticos. Patch por Alex Waygood.

  • gh-53502: Adiciona uma nova opção aware_datetime em plistlib para carregar ou despejar datetime consciente.

  • gh-113358: Corrige renderização de tracebacks com exceções com um __getattr__ quebrado

  • gh-113214: Corrige um AttributeError durante término do protocolo SSL asyncio em cenários SSL sobre SSL.

  • gh-113246: Atualiza o pip empacotado para 23.3.2.

  • gh-87264: Corrigido o método list() do tarfile para mostrar o tipo de arquivo.

  • gh-112182: asyncio.futures.Future.set_exception() agora transforma StopIteration em RuntimeError em vez de travar ou apresentar outro comportamento incorreto. Contribuição de patch de Jamie Phan.

  • gh-113225: Acelera pathlib.Path.glob() usando os.DirEntry.path sempre que possível.

  • gh-113149: Melhora a mensagem de erro quando um vetor JSON ou objeto contém uma vírgula final. Patch por Carson Radtke.

  • gh-113117: O módulo subprocess agora pode usar a função os.posix_spawn() com close_fds=True em plataformas onde posix_spawn_file_actions_addclosefrom_np está disponível. Patch por Jakub Kulik.

  • gh-113199: Faz http.client.HTTPResponse.read1 e http.client.HTTPResponse.readline fecharem E/S após ler todos os dados quando o comprimento do conteúdo for conhecido. Patch por Illia Volochii.

  • gh-113191: Adiciona suporte a os.fchmod() e um descritor de arquivo em os.chmod() no Windows.

  • gh-113188: Corrige shutil.copymode() e shutil.copystat() no Windows. Anteriormente, eles funcionavam de forma diferente se dst fosse um link simbólico: eles modificavam os bits de permissão do próprio dst em vez do arquivo para o qual ele aponta se follow_symlinks fosse true ou src não fosse um link simbólico, e não modificavam os bits de permissão se follow_symlinks fosse false e src fosse um link simbólico.

  • gh-113119: os.posix_spawn() agora aceita env=None, o que faz com que o processo recém-gerado use o ambiente de processo atual. Patch por Jakub Kulik.

  • gh-113202: Adiciona uma opção strict para batched() no módulo itertools.

  • gh-61648: Detecta números de linha de propriedades em doctests.

  • gh-113175: Sincroniza com importlib_metadata 7.0, incluindo anotações de tipo aprimoradas, problema corrigido com pacotes com links simbólicos em package_distributions, adicionado EntryPoints.__repr__, introduzido o script diagnose, adicionada a propriedade Distribution.origin e removido o acesso EntryPoint descontinuado por índice numérico (comportamento de tupla).

  • gh-59616: Adiciona suporte para os.lchmod() e o argumento follow_symlinks em os.chmod() no Windows. Observe que o valor padrão de follow_symlinks em os.lchmod() é False no Windows.

  • gh-112559: signal.signal() e signal.getsignal() não chamam mais repr em manipuladores chamáveis. asyncio.run() e asyncio.Runner.run() não chamam mais repr nos resultados da tarefa. Patch por Yilei Yang.

  • gh-112962: As funções do módulo dis adicionam informações de cache à instância Instruction em vez de criar instâncias falsas Instruction para representar as entradas de cache.

  • gh-112989: Reduz a sobrecarga para conectar soquetes com SelectorEventLoop do asyncio.

  • gh-112970: Usa closefrom() no Linux onde disponível (por exemplo, glibc-2.34), em vez de apenas FreeBSD.

  • gh-110190: Corrige estruturas ctypes com array na plataforma PPC64LE definindo MAX_STRUCT_SIZE como 64 em stgdict. Patch por Diego Russo.

  • gh-112540: A função statistics.geometric_mean() agora retorna zero para conjuntos de dados contendo um zero. Anteriormente, isso levantaria uma exceção.

  • gh-87286: Adicionados LOG_FTP, LOG_NETINFO, LOG_REMOTEAUTH, LOG_INSTALL, LOG_RAS e LOG_LAUNCHD ao módulo syslog, todos eles constantes usados no macOS.

  • gh-112800: Corrige asyncio SubprocessTransport.close() para não lançar PermissionError quando usado com executáveis setuid.

  • gh-51944: Adiciona as seguintes constantes ao módulo termios. Esses valores estão presentes nos cabeçalhos do sistema macOS: ALTWERASE, B14400, B28800, B7200, B76800, CCAR_OFLOW, CCTS_OFLOW, CDSR_OFLOW, CDTR_IFLOW, CIGNORE, CRTS_IFLOW, EXTPROC, IUTF8, MDMBUF, NL2, NL3, NOKERNINFO, ONOEOT, OXTABS, VDSUSP, VSTATUS.

  • gh-79325: Corrige um erro de recursão infinita na limpeza de tempfile.TemporaryDirectory() no Windows.

  • gh-94692: shutil.rmtree() agora captura apenas exceções OSError. Anteriormente, uma versão resistente a ataques de symlink de shutil.rmtree() podia ignorar ou passar para o manipulador de erros uma exceção arbitrária quando argumentos inválidos eram fornecidos.

  • gh-112736: O uso de símbolos del-safe em subprocess foi refatorado para permitir o uso em ambientes de construção multiplataforma.

  • gh-112727: Acelera pathlib.Path.absolute(). Patch por Barney Gale.

  • gh-74690: Aceleração de verificações de issubclass() em relação a protocolos runtime-checkable simples em cerca de 6%. Patch por Alex Waygood.

  • gh-74690: Aceleração de verificações de isinstance() em cerca de 20% para protocolos verificáveis em tempo de execução que têm apenas um membro chamável. Aceleração de verificações de issubclass() para esses protocolos em cerca de 10%. Patch por Alex Waygood.

  • gh-112645: Remoção de erro de descontinuação ao passar onerror para shutil.rmtree().

  • gh-112640: Adiciona o parâmetro kwdefaults a types.FunctionType para definir valores padrão de argumento nomeado.

  • gh-112622: Garante que o parâmetro name seja passado para o laço de eventos em asyncio.create_task().

  • gh-112618: Corrige um bug de armazenamento em cache relacionado a typing.Annotated. Annotated[str, True] não é mais idêntico a Annotated[str, 1].

  • gh-112334: Corrige uma regressão de desempenho no subprocess do 3.12 no Linux, onde ele não usaria mais a chamada de sistema de caminho rápido vfork() quando poderia devido a um bug lógico, em vez disso, voltando para o seguro, mas mais lento fork().

    Também foi corrigido um segundo bug de segurança potencial do 3.12.0. Se um valor de extra_groups=[] fosse passado para subprocess.Popen ou APIs relacionadas, a chamada de sistema setgroups(0, NULL) subjacente para limpar a lista de grupos não seria feita no processo filho antes de exec().

    Isso foi identificado por meio de inspeção de código no processo de correção do primeiro bug.

  • gh-110190: Corrige estruturas ctypes com array na plataforma Arm definindo MAX_STRUCT_SIZE como 32 em stgdict. Patch por Diego Russo.

  • gh-81194: Corrige uma falha em socket.if_indextoname() com valor específico (UINT_MAX). Corrigir um estouro de inteiro em socket.if_indextoname() em plataformas não Windows de 64 bits.

  • gh-112578: Corrige uma RuntimeWarning espúrio ao executar o módulo zipfile.

  • gh-112516: Atualiza a cópia empacotada do pip para a versão 23.3.1.

  • gh-112510: Adiciona readline.backend para os usos do backend readline (editline ou readline)

  • gh-112328: [Enum] Torna EnumDict, EnumDict.member_names, EnumType._add_alias_ e EnumType._add_value_alias_ públicos.

  • gh-112509: Corrige casos extremos que poderiam fazer com que uma chave estivesse presente nos atributos __required_keys__ e __optional_keys__ de um typing.TypedDict. Patch por Jelle Zijlstra.

  • gh-101336: Adiciona o parâmetro nomeado keep_alive para AbstractEventLoop.create_server() e BaseEventLoop.create_server().

  • gh-63284: Adicionado suporte para modo TLS-PSK (chave pré-compartilhada) ao módulo ssl.

  • gh-112414: Corrige regressão no Python 3.12 onde chamar repr() em um módulo que foi importado usando um loader personalizado poderia falhar com AttributeError. Patch por Alex Waygood.

  • gh-112358: Reverte alteração na inicialização struct.Struct que quebrou alguns casos de extensão de classes.

  • gh-112405: Otimiza pathlib.PurePath.relative_to(). Patch por Alex Waygood.

  • gh-94722: Corrige bug onde a comparação entre instâncias de DocTest falha se uma delas tiver None como seu lineno.

  • gh-112361: Acelera um pequeno punhado de métodos pathlib removendo alguns objetos temporários.

  • gh-112345: Melhora a mensagem de erro ao tentar chamar issubclass() contra um typing.Protocol que tem membros não-método. Patch por Randolf Scholz.

  • gh-112137: Altera a saída dis para exibir no-lineno como “–” em vez de “None”.

  • gh-112332: Descontinua o campo exc_type de traceback.TracebackException. Adiciona exc_type_str para substituí-lo.

  • gh-81620: Adiciona testes extras para random.binomialvariate()

  • gh-112292: Corrige uma falha em readline quando importado de um subinterpretador. Patch por Anthony Shaw

  • gh-77621: Melhora ligeiramente o tempo de importação do módulo pathlib adiando algumas importações. Patch por Barney Gale.

  • gh-112137: Altera a saída dis para exibir rótulos lógicos para alvos de salto em vez de deslocamentos.

  • gh-112139: Adiciona Signature.format() para formatar assinaturas para string com opções extras. E usá-lo em pydoc para renderizar assinaturas mais legíveis que tenham novas linhas entre parâmetros.

  • gh-112105: Faz readline.set_completer_delims() funcionar com libedit

  • gh-106922: Exibe várias linhas com traceback quando os erros abrangerem várias linhas.

  • gh-111874: Ao criar uma classe typing.NamedTuple, garante que __set_name__() seja chamado em todos os objetos que definem __set_name__ e existam nos valores do dicionário de classes da classe NamedTuple. Patch por Alex Waygood.

  • gh-68166: Adiciona suporte ao tipo de elemento “vsapi” em tkinter.ttk.Style.element_create().

  • gh-110275: Os métodos _replace() e __replace__() da tupla nomeada agora levantam TypeError em vez de ValueError para argumentos nomeados inválidos.

  • gh-99367: Não desorganiza sys.path[0] em pdb se safe_path estiver definido

  • gh-111615: Corrige uma regressão causada por uma correção em gh-93162, na qual você não conseguia configurar uma QueueHandler sem especificar manipuladores.

  • gh-75666: Corrige o comportamento do método unbind() do widget tkinter com dois argumentos. Anteriormente, widget.unbind(sequence, funcid) destruía a vinculação atual para sequence, deixando sequence desvinculado, e excluía o comando funcid. Agora ele remove apenas funcid da vinculação para sequence, mantendo outros comandos, e exclui o comando funcid. Ele deixa sequence desvinculado somente se funcid foi o último comando vinculado.

  • gh-67790: Implementa suporte básico de formatação (largura mínima, alinhamento, preenchimento) para fractions.Fraction.

  • gh-111049: Corrige travamento durante coleta de lixo do objeto buffer io.BytesIO.

  • gh-102980: Redireciona a saída do comando interact de pdb para o mesmo canal do depurador. Adiciona testes e melhore a documentação.

  • gh-102988: email.utils.getaddresses() e email.utils.parseaddr() agora retornam tuplas de dois elementos ('', '') em mais situações onde endereços de e-mail inválidos são encontrados em vez de potencialmente imprecisos valores. Adiciona o parâmetro strict opcional a estas duas funções: use strict=False para obter o comportamento antigo, aceitar entradas malformadas. getattr(email.utils, 'supports_strict_parsing', False) pode usar para verificar se o parâmetro strict está disponível. Patch por Thomas Dwyer e Victor Stinner para melhorar a correção CVE 2023-27043.

  • gh-52161: cmd.Cmd.do_help() agora limpa docstrings com inspect.cleandoc() antes de escrevê-las. Patch por Filip Łapkiewicz.

  • gh-82300: Adiciona o parâmetro track a multiprocessing.shared_memory.SharedMemory que permite usar blocos de memória compartilhada sem precisar registrar com o rastreador de recursos POSIX que os libera automaticamente na saída do processo.

  • gh-110109: Adiciona a classe privada pathlib._PurePathBase: uma classe base para pathlib.PurePath que omite certos métodos mágicos. Pode ser tornado público (junto com _PathBase) no futuro.

  • gh-109858: Protege zipfile de zipbomb “quoted-overlap”. Agora ele levanta BadZipFile ao tentar ler uma entrada que se sobrepõe a outra entrada ou diretório central.

  • gh-109786: Corrige possíveis vazamentos de referência e travamento ao reinserir o método __next__() de itertools.pairwise.

  • gh-91539: Melhoria de desempenho pequena (10 - 20%) e trivial de urllib.request.getproxies_environment(), normalmente útil quando há muitas variáveis de ambiente para analisar.

  • gh-103363: Adiciona o argumento somente-nomeado follow_symlinks a pathlib.Path.owner() e group(), com o padrão True.

  • gh-102130: Suporte para conclusão de tabulação em cmd para editline.

  • gh-99437: runpy.run_path() agora decodifica objetos caminho ou similares, garantindo que __file__ e sys.argv[0] do módulo que está sendo executado sejam sempre strings.

  • gh-104003: Adiciona warnings.deprecated(), um decorador para marcar funções descontinuadas para verificadores de tipo estático e para avisar sobre o uso de classes e funções obsoletas. Veja PEP 702. Patch por Jelle Zijlstra.

  • gh-103708: Torna o nome python codificado, um parâmetro configurável para que diferentes implementações do python possam substituí-lo em vez de fazer grandes diferenças em sysconfig.py

  • gh-66515: mailbox.MH agora oferece suporte a pastas que não contêm um arquivo .mh_sequences (por exemplo, pastas de cache IMAP do Claws Mail). Patch por Serhiy Storchaka.

  • gh-83162: Renomeado re.error para PatternError para maior clareza, e mantido re.error para compatibilidade com versões anteriores. Patch por Matthias Bussonnier e Adam Chhina.

  • gh-91133: Corrige um bug na limpeza de tempfile.TemporaryDirectory, que agora não desreferencia mais links simbólicos ao contornar erros de permissão do sistema de arquivos.

  • bpo-43153: No Windows, tempfile.TemporaryDirectory mascarava anteriormente um PermissionError com NotADirectoryError durante a limpeza de diretório. Agora ele levanta corretamente PermissionError se os erros não forem ignorados. Patch por Andrei Kulakov e Ken Jin.

  • bpo-32731: getpass.getuser() agora levanta OSError para todas as falhas em vez de ImportError em sistemas sem o módulo pwd ou KeyError se o banco de dados de senhas estiver vazio.

  • bpo-34321: mmap.mmap agora tem um parâmetro trackfd no Unix; se for False, o descritor de arquivo especificado por fileno não será duplicado.

  • bpo-35332: A função shutil.rmtree() agora ignora erros ao chamar os.close() quando ignore_errors é True, e os.close() não é mais tentado novamente após erro.

  • bpo-35928: io.TextIOWrapper agora manipula corretamente o buffer de decodificação após read() e write().

  • bpo-26791: shutil.move() agora move um link simbólico para um diretório quando esse diretório é o alvo do link simbólico. Isso fornece o mesmo comportamento do comando mv shell. O comportamento anterior gerou uma exceção. Patch por Jeffrey Kintscher.

  • bpo-41422: Corrigidos vazamentos de memória de pickle.Pickler e pickle.Unpickler envolvendo referências cíclicas por meio do mapeamento de memorando interno.

  • bpo-19821: A função pydoc.ispackage() foi descontinuada.

  • bpo-40262: O método ssl.SSLSocket.recv_into() não requer mais o argumento buffer para implementar __len__ e suporta buffers com tamanho de item arbitrário.

  • bpo-39912: warnings.filterwarnings() e warnings.simplefilter() agora levantam exceções apropriadas em vez de AssertionError. Patch foi contribuição de Rémi Lapeyre.

  • bpo-37260: Corrigida uma condição de corrida em shutil.rmtree() na qual entradas de diretório removidas por outro processo ou thread enquanto shutil.rmtree() está em execução podem fazer com que ele levante FileNotFoundError. Patch por Jeffrey Kintscher.

  • bpo-36959: Corrigidas algumas mensagens de erro para combinações de strings de formato ISO inválidas em strptime() que se referiam a diretivas não contidas na string de formato. Patch por Gordon P. Hemsley.

  • bpo-18060: Corrigido um problema de herança de classe que pode causar falhas de segmentação ao derivar dois ou mais níveis de subclasses de uma classe base de Structure ou Union.

  • bpo-29779: Adicionada uma nova variável de ambiente PYTHON_HISTORY para definir o local de um arquivo .python_history.

  • bpo-21360: mailbox.Maildir agora ignora arquivos com um ponto inicial.

Documentação

  • gh-111699: Realoca o aviso de descontinuação de smtpd para sua própria seção em vez de em locale no documento O que há de novo no Python 3.12

  • gh-110746: Marcação aprimorada para opções/valores válidos para os métodos ttk.treeview.column e ttk.treeview.heading, e para Layouts.

  • gh-95649: Document que o módulo asyncio contém código retirado de v0.16.0 do projeto uvloop, bem como as informações de licenciamento do MIT necessárias.

Testes

  • gh-111798: Desabilita test_super_deep() de test_call em construções pydebug em WASI; a profundidade da pilha é muito pequena para tornar o teste útil.

  • gh-111801: Reduz o limite de recursão em test_isinstance para test_infinitely_many_bases(). Isso evita um estouro de pilha em uma construção pydebug de WASI.

  • gh-111802: Especifica uma profundidade de recursão baixa para test_bad_getattr() em test.pickletester para evitar esgotar a pilha em uma construção pydebug para WASI.

  • gh-44626: Corrige os.path.isabs() retornando incorretamente True quando recebe um caminho que começa com exatamente uma barra (invertida) no Windows.

    Corrige pathlib.PureWindowsPath.is_absolute() retornando incorretamente False para alguns caminhos que começam com duas barras (invertidas).

  • gh-113633: Use estado do módulo para o módulo de extensão _testcapi.

  • gh-109980: Corrige test_tarfile_vs_tar em test_shutil para macOS, onde o tar do sistema pode incluir mais informações no arquivo do que shutil.make_archive.

  • gh-112769: Os testes agora comparam corretamente a versão zlib quando zlib.ZLIB_RUNTIME_VERSION contém sufixos não inteiros. Por exemplo, zlib-ng define a versão como 1.3.0.zlib-ng.

  • gh-112334: Adiciona um teste de regressão para verificar se vfork() é usado quando esperado por subprocess em sistemas POSIX habilitados para vfork (Linux).

  • gh-108927: Corrigida a dependência de ordem na execução de testes no mesmo processo quando um teste que tem submódulos (por exemplo, test_importlib) segue um teste que importa seu submódulo (por exemplo, test_importlib.util) e precede um teste (por exemplo, test_unittest ou test_compileall) que usa esse submódulo.

  • bpo-40648: Modos de teste que o arquivo pode obter com chmod() no Windows.

Construção

  • gh-114013: Corrige Tools/wasm/wasi.py para não incluir o caminho para python.wasm como parte de HOSTRUNNER. A variável de ambiente tem como objetivo especificar como executar apenas o host WASI, tendo python.wasm e sinalizadores relevantes anexados ao HOSTRUNNER. Isso corrige o funcionamento de make test.

  • gh-113258: Alterada a construção do Windows para gravar módulos congelados gerados na árvore de construção em vez da árvore de fontes.

  • gh-112305: Corrigida a etapa check-clean-src realizada em construções fora da árvore para detectar arquivos $(srcdir)/Python/frozen_modules/*.h errantes e recomendou etapas de limpeza apropriadas da árvore de fontes para obter uma construção funcional novamente.

  • gh-112536: Adiciona suporte para sanitizador de thread (TSAN)

  • gh-112867: Corrige a construção para o caso em que WITH_PYMALLOC_RADIX_TREE=0 definido.

  • gh-103065: Apresenta Tools/wasm/wasi.py para simplificar a execução de uma construção WASI.

  • bpo-11102: As funções os.major(), os.makedev() e os.minor() agora estão disponíveis no HP-UX v3.

  • bpo-36351: Não defina ipv6type ao fazer compilação cruzada.

Windows

  • gh-114096: Os privilégios de processo que são ativados para criar junções de diretório agora são restaurados posteriormente, evitando alterações de comportamento em outras partes do programa.

  • gh-111877: As chamadas os.stat() estavam retornando valores de tempo incorretos para arquivos que não podiam ser acessados diretamente.

  • gh-111973: Atualiza o instalador do Windows para usar o SQLite 3.44.2.

  • gh-113009: multiprocessing: No Windows, corrige uma condição de corrida em Process.terminate(): não define mais o atributo returncode para sempre chamar WaitForSingleObject() em Process.wait(). Anteriormente, às vezes o processo ainda estava em execução após TerminateProcess() mesmo se GetExitCodeProcess() não fosse STILL_ACTIVE. Patch por Victor Stinner.

  • gh-86179: Corrige cálculos de caminho ao iniciar o Python no Windows por meio de um link simbólico.

  • gh-71383: Atualiza Tcl/Tk no instalador do Windows para 8.6.13 com um patch para suprimir avisos incorretos de ThemeChanged.

  • gh-111650: Garante que a variável do pré-processador Py_GIL_DISABLED seja definida em pyconfig.h para que módulos de extensão escritos em C possam usá-la.

  • gh-112278: Reduz o custo de tempo para algumas funções em platform no Windows se o usuário atual não tiver permissão para o WMI.

  • gh-73427: Deprecate sys._enablelegacywindowsfsencoding(). Use PYTHONLEGACYWINDOWSFSENCODING instead. Patch by Inada Naoki.

  • gh-87868: Classifica e remove corretamente variáveis de ambiente duplicadas em _winapi.CreateProcess().

  • bpo-37308: Corrige mojibake em mmap.mmap ao usar um argumento tagname não ASCII no Windows.

macOS

  • gh-113666: Adiciona as seguintes constantes ao módulo stat: UF_SETTABLE, UF_TRACKED, UF_DATAVAULT, SF_SUPPORTED, SF_SETTABLE, SF_SYNTHETIC, SF_RESTRICTED, SF_FIRMLINK e SF_DATALESS. Os valores UF_SETTABLE, SF_SUPPORTED, SF_SETTABLE e SF_SYNTHETIC estão disponíveis apenas no macOS.

  • gh-113536: os.waitid() agora está disponível no macOS

  • gh-110459: Executar configure ... --with-openssl-rpath=X/Y/Z não falha mais em detectar OpenSSL no macOS.

  • gh-74573: Documenta que dbm.ndbm pode corromper silenciosamente arquivos DBM em atualizações ao exceder limites de plataforma não documentados e pode travar (falha de segmentação) ao ler um arquivo corrompido. (FB8919203)

  • gh-65701: A ferramenta freeze não funciona com construções de framework do Python. Documente isso e faça sair mais cedo ao executar a ferramenta com tal construção.

  • gh-87277: webbrowser: Não procura navegadores X11 no macOS. Geralmente, eles não são usados e procurá-los pode resultar na inicialização do XQuartz, mesmo que ele não seja usado de outra forma.

  • gh-111973: Atualiza o instalador do macOS para usar o SQLite 3.44.2.

  • gh-108269: Define CFBundleAllowMixedLocalizations como true no Info.plist para o framework, Python.app incorporado e IDLE.app com instalações do framework no macOS. Isso permite que as aplicações selecionem o local preferido do usuário quando for diferente do inglês.

  • gh-102362: Garante que o resultado de sysconfig.get_plaform() inclua pelo menos uma versão principal e secundária, mesmo que MACOSX_DEPLOYMENT_TARGET esteja definido como apenas uma versão principal durante a construção para corresponder ao formato esperado pelo pip.

  • gh-110017: Desabilita um teste de estresse de tratamento de sinal no macOS devido a um bug no macOS (FB13453490).

  • gh-110820: Garante que as definições do pré-processador para ALIGNOF_MAX_ALIGN_T, SIZEOF_LONG_DOUBLE e HAVE_GCC_ASM_FOR_X64 estejam corretas para construções Universal 2 no macOS.

  • gh-109981: Usa /dev/fd no macOS para determinar o número de arquivos abertos em test.support.os_helper.fd_count para evitar uma falha com descritores de arquivo “guarded” ao sondar arquivos abertos.

IDLE

  • gh-72284: Melhora as listas de recursos, atalhos de teclado do editor e atalhos de teclado do shell no documento do IDLE.

  • gh-113903: Corrige a falha rara de test.test_idle, em test_configdialog.

  • gh-113729: Corrige o bug do menu “Help -> IDLE Doc” em 3.11.7 e 3.12.1.

  • gh-113269: Corrige o travamento do test_editor no macOS Catalina.

  • gh-112898: Corrige o processamento de arquivos não salvos ao sair do IDLE no macOS.

  • bpo-13586: Insere o texto selecionado ao abrir a caixa de diálogo “Replace”.

API C

Python 3.13.0 alpha 2

Data de lançamento: 2023-11-22

Núcleo e embutidos

  • gh-112243: Não inclua comentários nas expressões do depurador com f-string. Patch por Pablo Galindo

  • gh-112287: Otimiza ligeiramente o interpretador nível 2 (uop) carregando apenas oparg e operand quando necessário. Também dobra o limite de tamanho de rastreamento novamente, para 512 desta vez.

  • gh-112266: Altera as docstrings de __dict__ e __weakref__.

  • gh-111807: Reduz a profundidade máxima da pilha do analisador para 1000 em construções de depuração WASI.

  • gh-111798: Quando o Python é construído no modo de depuração, define o limite de recursão C para 500 em vez de 1500. Uma construção de depuração provavelmente é construída com baixo nível de otimização, o que implica maior uso de memória de pilha do que uma construção de lançamento. Patch por Victor Stinner.

  • gh-106529: Habilita a tradução de FOR_ITER não especializado para o Nível 2.

  • gh-111916: Torna os módulos relacionados ao hashlib seguros para thread sem a GIL

  • gh-81137: Descontinua a atribuição ao campo __code__ de uma função quando o novo objeto de código for de um tipo incompatível (por exemplo, de um gerador para uma função simples).

  • gh-79932: Levanta uma exceção se frame.clear() for chamado em um quadro suspenso.

  • gh-81925: Implementa IDs de thread nativas para GNU KFreeBSD.

  • gh-111843: Usa o backoff exponencial para reduzir o número de tentativas de otimização de nível 2 com falha em mais de 99%.

  • gh-110829: Unir uma thread agora garante que a thread do sistema operacional subjacente tenha saído. Isso é necessário para fork() mais seguro em processos multithread.

  • gh-109369: Certifica-se de que os rastreamentos de nível 2 sejam desotimizados se o código for instrumentado

  • gh-111772: Especializa cargas e armazenamentos de slot para _Py_T_OBJECT, bem como Py_T_OBJECT_EX

  • gh-111666: Acelera BaseExceptionGroup.derive(), BaseExceptionGroup.subgroup() e BaseExceptionGroup.split() alterando como eles analisam os argumentos passados.

  • gh-111654: Corrige o travamento do tempo de execução quando algum erro acontece no opcode LOAD_FROM_DICT_OR_DEREF.

  • gh-111623: Adiciona suporte para compartilhar tuplas entre interpretadores usando a API de interpretador cruzado. Patch por Anthony Shaw.

  • gh-111354: O oparg de YIELD_VALUE agora é 1 se a instrução for parte de um yield-from ou await, e 0 caso contrário.

    O estado do quadro SUSPENDED agora é dividido em SUSPENDED e SUSPENDED_YIELD_FROM. Isso simplifica o código em _PyGen_yf.

  • gh-111520: Mescla os interpretadores nível 1 (bytecode) e nível 2 (micro-ops), movendo o laço do interpretador nível 2 e alterne para _PyEval_EvalFrameDefault() em Python/ceval.c. O arquivo Python/executor.c desapareceu. Além disso, as macros TIER_ONE e TIER_TWO agora são manipuladas pelo gerador de código.

    Cuidado! Isso altera as variáveis de ambiente para habilitar micro-ops e sua depuração para PYTHON_UOPS e PYTHON_LLTRACE.

  • gh-109181: Acelera a criação do objeto Traceback calculando preguiçosamente o número da linha. Patch por Pablo Galindo

  • gh-111420: Permite comentários de tipo em instruções with entre parênteses

  • gh-111438: Adicione suporte para compartilhar floats entre interpretadores usando a API de interpretador cruzado. Patch por Anthony Shaw.

  • gh-111435: Adiciona suporte para compartilhar True e False entre interpretadores usando a API de interpretador cruzado. Patch por Anthony Shaw.

  • gh-102388: Corrige um bug em que os codecs iso2022_jp_3 e iso2022_jp_2004 liam fora dos limites

  • gh-111366: Corrige um problema no codeop que estava fazendo com que exceções SyntaxError geradas na presença de sintaxe inválida não contivessem mensagens de erro precisas. Patch por Pablo Galindo

  • gh-111380: Corrige um bug que estava fazendo com que SyntaxWarning aparecesse duas vezes ao analisar se uma sintaxe inválida fosse encontrada posteriormente. Patch por Pablo Galindo

  • gh-111374: Adicionada uma nova variável de ambiente PYTHON_FROZEN_MODULES. Determina se os módulos congelados são ou não ignorados pelo mecanismo de importação, equivalente à opção de linha de comando -X frozen_modules.

  • gh-111354: Remove oparg de YIELD_VALUE. Altera oparg de RESUME para incluir informações sobre o except-depth. Essas alterações possibilitam simplificar o código no fechamento do gerador.

  • gh-94438: Corrige uma regressão que impedia o salto entre is None e is not None durante a depuração. Patch por Savannah Ostrowski.

  • gh-67224: Mostra linhas de origem em tracebacks ao usar a opção -c ao executar Python. Patch por Pablo Galindo

  • gh-111123: Corrige um bug em que uma declaração global em um bloco except é rejeitada quando o global é usado no bloco else.

  • gh-110938: Corrige mensagens de erro para blocos indentados com funções e classes com parâmetros de tipo genérico. Patch por Pablo Galindo

  • gh-109214: Remove atualizações desnecessárias de ponteiros de instruções antes de retornar de quadros.

  • gh-110912: Exibe corretamente o traceback para exceções MemoryError usando o módulo traceback. Patch por Pablo Galindo

  • gh-109894: Corrige falha devido a MemoryError estático inicializado incorretamente no subinterpretador.

  • gh-110892: Retorna NULL para eventos PyTrace_RETURN causados por uma exceção

  • gh-110864: Corrige análise de argumento por _PyArg_UnpackKeywordsWithVararg para funções que definem parâmetros posicionais-ou-nomeados, argumentos variáveis e somente-nomeados.

  • gh-109094: Substitui prev_instr no quadro do interpretador por instr_ptr que aponta para o início da instrução que está sendo executada no momento (ou será executada quando o quadro for retomado).

  • gh-110805: Permite que o repl mostre o código-fonte e tracebacks completos. Patch por Pablo Galindo

  • gh-110722: Adiciona PYTHON_PRESITE=package.module para importar um módulo no início do ciclo de vida do interpretador antes de site.py ser executado. O Python precisa ser construído no modo de depuração para que esta opção exista.

  • gh-110481: Implementa a contagem de referências tendenciosa em construções --disable-gil.

  • gh-110543: Corrige regressão no Python 3.12 onde types.CodeType.replace() produziria um objeto de código quebrado se chamado em um objeto código de módulo ou classe que contém uma compreensão. Patch por Jelle Zijlstra.

  • gh-89519: Removidos os descritores encadeados de classmethod (introduzidos em bpo-19072). Isso não pode mais ser usado para encapsular outros descritores como property. O design principal desse recurso era falho e causava uma série de problemas posteriores. Para “passar” um classmethod, considere usar o atributo __wrapped__ que foi adicionado no Python 3.10.

  • gh-103615: Usa eventos locais para rastreamento de opcode

  • bpo-46657: Adiciona suporte ao alocador de memória mimalloc.

  • gh-106718: Quando PyConfig.stdlib_dir é definido explicitamente, ele agora é respeitado e não será substituído por PyConfig.home.

  • gh-106905: Corrige o SystemError incorreto sobre a incompatibilidade de profundidade de recursão do construtor AST.

  • gh-100445: Melhora a mensagem de erro para strings não terminadas com escapes.

  • bpo-45759: Melhoradas as mensagens de erro para instruções elif/else que não correspondem a nenhuma instrução válida. Patch por Jeremiah Vivian.

Biblioteca

  • gh-111942: Corrige o SystemError no construtor TextIOWrapper com o argumento “errors” não codificável no modo não de depuração.

  • gh-111995: Adicionada a constante NI_IDN ao módulo socket quando presente em C no momento da compilação para uso com socket.getnameinfo().

  • gh-109538: Emite mensagem de aviso em vez de exibir RuntimeError quando o laço de eventos já foi fechado em StreamWriter.__del__().

  • gh-111942: Corrige travamentos em io.TextIOWrapper.reconfigure() ao passar argumentos inválidos, por exemplo, codificação não string.

  • gh-111460: curses: restaura o suporte a caracteres amplos (incluindo curses.unget_wch() e get_wch()) no macOS, que estava indisponível devido a uma regressão no Python 3.12.

  • gh-103791: contextlib.suppress agora oferece suporte à supressão de exceções levantadas como parte de um BaseExceptionGroup, além do suporte recente para ExceptionGroup.

  • gh-111835: A classe mmap.mmap agora tem um método seekable() que pode ser usado quando um objeto arquivo ou similar pesquisável é necessário. O método seek() agora retorna a nova posição absoluta. Patch por Donghee Na.

  • gh-111804: Remove posix.fallocate() em WASI, pois o posix_fallocate() subjacente não está disponível na visualização WASI2.

  • gh-111841: Corrige argumentos truncados em um caractere nulo incorporado em os.putenv() e os.unsetenv() no Windows.

  • gh-111768: wsgiref.util.is_hop_by_hop() agora é exposto corretamente em __all__.

  • gh-80731: Evita executar a função padrão em cmd.Cmd em um bloco except

  • gh-111541: Corrige doctest para subclasses não embutidas de SyntaxError.

  • gh-111719: Adiciona validação de argumento extra para o comando alias em pdb

  • gh-111482: time: Torna as funções time.clock_gettime() e time.clock_gettime_ns() até 2x mais rápidas por convenção de chamada mais rápida. Patch por Victor Stinner.

  • gh-110894: Chama manipulador de exceção de laço para exceções em client_connected_cb de asyncio.start_server() para que as aplicações possam lidar com isso. Patch por Kumar Aditya.

  • gh-111531: Corrige vazamentos de referência nos métodos bind_class() e bind_all() dos widgets tkinter.

  • gh-111246: asyncio.loop.create_unix_server() agora removerá automaticamente o soquete Unix quando o servidor for fechado.

  • gh-111356: Adicionados io.text_encoding(), io.DEFAULT_BUFFER_SIZE e io.IncrementalNewlineDecoder para io.__all__.

  • gh-66425: Remove o código para definir o cabeçalho REMOTE_HOST do módulo wsgiref, pois ele é inacessível. Este cabeçalho é usado por motivos de desempenho, o que não é necessário no módulo wsgiref.

  • gh-111429: Acelera pathlib.PurePath.relative_to() e is_relative_to().

  • gh-111342: Corrigido erro de digitação em math.sumprod().

  • gh-68166: Remove menção de tipo de elemento “vsapi” não suportado em tkinter.ttk.Style.element_create(). Adiciona testes para element_create() e outros métodos ttk.Style. Adiciona exemplos para element_create() na documentação.

  • gh-111388: Adiciona parâmetro show_group para traceback.format_exception_only(), que permite formatar instâncias ExceptionGroup.

  • gh-79033: Outra tentativa de corrigir asyncio.Server.wait_closed(). Agora ela bloqueia até que ambas as condições sejam verdadeiras: o servidor é fechado, e não há mais conexões ativas. (Isso significa que em alguns casos onde na versão 3.12.0 essa função retornaria incorretamente imediatamente, agora ela bloqueará; em particular, quando não há conexões ativas, mas o servidor ainda não foi fechado.)

  • gh-111259: Otimiza curingas recursivos em pathlib.

  • gh-111295: Corrige time não verificando erros ao inicializar.

  • gh-111253: Adiciona verificação de erros durante a inicialização do módulo _socket.

  • gh-111251: Corrige _blake2 não verificando erros ao inicializar.

  • gh-111233: Corrige select não verificando erros ao inicializar.

  • gh-111230: Corrige ssl não verificando erros ao inicializar.

  • gh-111174: Corrige travamento em io.BytesIO.getbuffer() chamado repetidamente para BytesIO vazio.

  • gh-111187: Adia versão de remoção para locale.getdefaultlocale() para Python 3.15.

  • gh-111159: Corrige comparação de saída doctest para exceções com notas.

  • gh-110910: Corrige manipulação de estado inválido em asyncio.TaskGroup e asyncio.Timeout. Eles agora geram RuntimeError adequado se forem usados incorretamente e são deixados em estado consistente depois disso.

  • gh-111092: Faz turtledemo ser executado sem root padrão habilitado.

  • gh-110944: Adiciona suporte a apelido e variáveis de conveniência para completamento automático de pdb

  • gh-110745: Adicionado o parâmetro newline para pathlib.Path.read_text(). Patch por Junya Okabe.

  • gh-84583: Faz pdb entrar no modo post-mortem mesmo para SyntaxError

  • gh-80675: Define f_trace_lines = True em todos os quadros em pdb.set_trace()

  • gh-110771: Expõe as partes de configuração e limpeza de asyncio.run_forever() como os métodos autônomos asyncio.run_forever_setup() e asyncio.run_forever_cleanup(). Isso permite uma integração mais estreita com laços de eventos da GUI.

  • gh-110774: Suporte para definir o kwarg loop_factory asyncio.Runner em unittest.IsolatedAsyncioTestCase

  • gh-110392: Corrige tty.setraw() e tty.setcbreak(): anteriormente eles retornavam uma lista parcialmente modificada dos atributos tty originais. tty.cfmakeraw() e tty.cfmakecbreak() agora fazem uma cópia da lista de caracteres especiais antes de modificá-la.

  • gh-59013: Torna o número de linhas do ponto de interrupção da função mais preciso em pdb

  • gh-88434: Emite aviso de descontinuação para números não inteiros em funções e métodos gettext que consideram formas plurais, mesmo que a tradução não tenha sido encontrada.

  • gh-110395: Garante que os objetos select.kqueue() apareçam corretamente como fechados em filhos bifurcados, para evitar operações em um descritor de arquivo inválido.

  • gh-110196: Adiciona o método __reduce__ a IPv6Address para manter scope_id

  • gh-109747: Melhora os erros para padrões look-behind não suportados. Agora re.error é levantada em vez de OverflowError ou RuntimeError para largura muito grande do padrão look-behind.

  • gh-109466: Adiciona a propriedade ipaddress.IPv4Address.ipv6_mapped, que retorna o endereço IPv6 mapeado para IPv4.

  • gh-85098: Implementa a CLI do módulo symtable e melhorar o repr de Symbol.

  • gh-108791: Tratamento de erros aprimorado na interface de linha de comando pdb, fazendo com que ela produza mensagens de erro mais concisas.

  • gh-105931: Altera compileall para remover apenas o prefixo stripdir do caminho completo registrado no arquivo .pyc compilado, quando o prefixo corresponder ao início do caminho completo em sua totalidade. Quando o prefixo não corresponder, nenhuma remoção será realizada e um aviso para esse efeito será exibido.

    Anteriormente, todos os componentes de caminho do prefixo stripdir que correspondiam ao caminho completo eram removidos, enquanto aqueles que não correspondiam eram deixados sozinhos (incluindo aqueles intercalados entre componentes correspondentes).

  • gh-107431: Cria os tipos DictProxy e ListProxy em tipos Generic Alias de multiprocessing.managers para uso [] em contextos de tipagem.

  • gh-72904: Adiciona glob.translate(). Esta função converte um nome de caminho com curingas de estilo shell em uma expressão regular.

  • gh-90026: Define USE_XATTRS no Cygwin para que as funções relacionadas a XATTR no módulo os fiquem disponíveis.

  • gh-90890: Novos métodos mailbox.Maildir.get_info(), mailbox.Maildir.set_info(), mailbox.Maildir.get_flags(), mailbox.Maildir.set_flags(), mailbox.Maildir.add_flag(), mailbox.Maildir.remove_flag(). Esses métodos aceleram o acesso às informações e/ou sinalizadores de uma mensagem e são úteis quando não é necessário acessar o conteúdo da mensagem, como ao iterar sobre um Maildir para encontrar mensagens com sinalizadores específicos.

  • gh-102956: Corrige o retorno de strings de bytes vazias após uma busca no módulo zipfile

  • gh-102895: Adicionado um parâmetro local_exit para code.interact() para evitar que exit() e quit fechem sys.stdin e levantem SystemExit.

  • gh-97928: Altera o comportamento de tkinter.Text.count(). Agora ele sempre retorna um inteiro se uma ou menos opções de contagem forem especificadas. Anteriormente, ele podia retornar uma única contagem como uma tupla de 1 elemento, um inteiro (somente se a opção "update" fosse especificada) ou None se nenhum item fosse encontrado. O resultado agora é o mesmo se wantobjects for definido como 0.

  • gh-96954: Troca o armazenamento dos nomes de pontos de código unicode para usar uma estrutura de dados diferente, um grafo de palavras acíclicas direcionadas. Isso torna a biblioteca compartilhada unicodedata cerca de 440 KiB menor. Contribuição de Carl Friedrich Bolz-Tereick usando código do projeto PyPy.

  • gh-73561: Omite o escopo da interface de um endereço IPv6 quando usado como cabeçalho de host por http.client.

  • gh-86826: zipinfo agora oferece suporte ao intervalo completo de valores na string TZ determinado pelo RFC 8536 e detecta todos os formatos inválidos. Ambas as implementações Python e C agora levantam exceções do mesmo tipo em dados inválidos.

Testes

  • gh-111808: Faz o valor padrão de test.support.infinite_recursion() ser condicional com base em se otimizações foram usadas ao compilar o interpretador. Isso ajuda com plataformas como WASI cujo tamanho de pilha é muito restrito em construções de depuração.

  • gh-110722: A coleta de cobertura de linha de bibliotecas padrão dentro do conjunto de testes de regressão agora é precisa, bem como muito mais rápida. Patch por Łukasz Langa.

  • gh-110367: Torna a opção regrtest --verbose3 compatível com as opções --huntrleaks -jN. O comando ./python -m test -j1 -R 3:3 --verbose3 agora funciona como esperado. Patch por Victor Stinner.

  • gh-111165: Remove as funções não mais utilizadas run_unittest() e run_doctest() do módulo test.support.

  • gh-110932: Corrige regrtest se a variável de ambiente SOURCE_DATE_EPOCH estiver definida: usar o valor da variável como a semente aleatória. Patch por Victor Stinner.

  • gh-110995: test_gdb: Corrige a detecção de gdb construído sem suporte a scripts Python. Patch por Victor Stinner.

  • gh-110918: Os padrões de correspondência de casos de teste especificados pelas opções --match, --ignore, --matchfile e --ignorefile agora são testados na ordem de especificação, e a última correspondência determina se o caso de teste deve ser executado ou ignorado.

  • gh-108747: Adiciona o teste de unidade para os ganchos usercustomize e sitecustomize de site.

Construção

  • gh-96954: Faz make regen-unicodedata funcionar para construções fora da árvore do CPython.

  • gh-112088: Adiciona o script Tools/build/regen-configure.sh para regenerar o configure com uma imagem de contêiner do Ubuntu. A imagem do contêiner quay.io/tiran/cpython_autoconf:271 (tiran/cpython_autoconf) não é mais usada. Patch por Victor Stinner.

  • gh-111046: Para wasi-threads, a memória agora é exportada para corrigir problemas de compatibilidade com alguns tempos de execução wasm.

  • gh-110828: AIX 32 bits precisa de -latomic para construir o módulo de extensão _testcapi.

  • gh-85283: As extensões C errno, md5, resource, winsound, _ctypes_test, _multiprocessing.posixshmem, _scproxy, _stat, _testimportmultiple e _uuid agora são criadas com a API C limitada. Patch por Victor Stinner.

Windows

  • gh-111856: Corrige fstat() em sistemas de arquivos que não oferecem suporte a solicitações de ID de arquivo. Isso inclui FAT32 e exFAT.

  • gh-111293: Corrige os.DirEntry.inode eliminando 64 bits mais altos de uma ID de arquivo em alguns sistemas de arquivos no Windows.

  • gh-110913: O WindowsConsoleIO agora divide corretamente buffers grandes sem dividir sequências UTF-8.

macOS

  • gh-59703: Para construções de framework macOS, em getpath.c use a função dladdr do sistema para encontrar o caminho para a biblioteca compartilhada em vez de depender de APIs macOS descontinuadas.

  • gh-110950: Atualiza o instalador macOS para incluir uma correção Tcl/Tk upstream para o aviso Secure coding is not enabled for restorable state! encontrado no Tkinter no macOS 14 Sonoma.

  • gh-111015: Garante que IDLE.app e Python Launcher.app sejam instalados com as permissões apropriadas em construções macOS.

  • gh-71383: Atualiza o instalador do macOS para incluir uma correção Tcl/Tk upstream para o erro ttk::ThemeChanged encontrado no Tkinter.

  • gh-92603: Atualiza o instalador do macOS para incluir uma correção aceita pelo Tcl/Tk upstream para uma falha encontrada após a destruição da primeira instância tkinter.Tk().

IDLE

  • bpo-35668: Adiciona docstrings ao módulo depurador IDLE. Corrigir dois bugs: inicializar Idb.botframe (deve estar em Bdb); em Idb.in_rpc_code, verificar se prev_frame é None antes de tentar usá-lo. Expandir bastante o test_debugger.

Ferramentas/Demos

  • gh-111903: Clínica de Argumentos agora oferece suporte à diretiva @critical_section que instrui a Clínica de Argumentos a gerar uma seção crítica em torno da chamada de função, que trava o objeto self em construções --disable-gil. Patch por Sam Gross.

API C

  • gh-112026: Adiciona novamente a função privada _PyThreadState_UncheckedGet() como um apelido para a nova função pública PyThreadState_GetUnchecked(). Patch por Victor Stinner.

  • gh-112026: Restaure a função _PyDict_GetItemStringWithError() removida. Ela é usada pelo numpy. Patch por Victor Stinner.

  • gh-112026: Restaure as funções privadas, macros e estruturas da API C removidas que não têm substituição simples por enquanto:

    • _PyDict_GetItem_KnownHash()

    • _PyDict_NewPresized()

    • _PyHASH_BITS

    • _PyHASH_IMAG

    • _PyHASH_INF

    • _PyHASH_MODULUS

    • _PyHASH_MULTIPLIER

    • _PyLong_Copy()

    • _PyLong_FromDigits()

    • _PyLong_New()

    • _PyLong_Sign()

    • _PyObject_CallMethodId()

    • _PyObject_CallMethodNoArgs()

    • _PyObject_CallMethodOneArg()

    • _PyObject_CallOneArg()

    • _PyObject_EXTRA_INIT

    • _PyObject_FastCallDict()

    • _PyObject_GetAttrId()

    • _PyObject_Vectorcall()

    • _PyObject_VectorcallMethod()

    • _PyStack_AsDict()

    • _PyThread_CurrentFrames()

    • _PyUnicodeWriter structure

    • _PyUnicodeWriter_Dealloc()

    • _PyUnicodeWriter_Finish()

    • _PyUnicodeWriter_Init()

    • _PyUnicodeWriter_Prepare()

    • _PyUnicodeWriter_PrepareKind()

    • _PyUnicodeWriter_WriteASCIIString()

    • _PyUnicodeWriter_WriteChar()

    • _PyUnicodeWriter_WriteLatin1String()

    • _PyUnicodeWriter_WriteStr()

    • _PyUnicodeWriter_WriteSubstring()

    • _PyUnicode_AsString()

    • _PyUnicode_FromId()

    • _PyVectorcall_Function()

    • _Py_IDENTIFIER()

    • _Py_c_abs()

    • _Py_c_diff()

    • _Py_c_neg()

    • _Py_c_pow()

    • _Py_c_prod()

    • _Py_c_quot()

    • _Py_c_sum()

    • _Py_static_string()

    • _Py_static_string_init()

    Patch por Victor Stinner.

  • gh-112026: Adiciona novamente os includes <ctype.h> e <unistd.h> em Python.h, mas não os inclui na versão limitada da API C 3.13 e mais recentes. Patch por Victor Stinner.

  • gh-111956: Adiciona API de inicialização única interna: _PyOnceFlag e _PyOnceFlag_CallOnce.

  • gh-111262: Adiciona funções PyDict_Pop() e PyDict_PopString(): remover uma chave de um dicionário e, opcionalmente, retornar o valor removido. Isso é semelhante a dict.pop(), mas sem o valor padrão e não levantando KeyError se a chave estiver faltando. Patch por Stefan Behnel e Victor Stinner.

  • gh-111863: Renomeia Py_NOGIL para Py_GIL_DISABLED. Patch por Hugo van Kemenade.

  • gh-111138: Adiciona as funções PyList_Extend() e PyList_Clear(): semelhantes aos métodos Python list.extend() e list.clear(). Patch por Victor Stinner.

  • gh-108765: No Windows, Python.h não inclui mais o arquivo de cabeçalho padrão <stddef.h>. Se necessário, ele deve ser incluído explicitamente. Patch por Victor Stinner.

  • gh-111569: Implementa “Python Critical Sections” de PEP 703. Essas são macros para ajudar a substituir a GIL por travas por objeto na construção com --disable-gil do CPython. As macros são no-ops na construção padrão.

  • gh-111506: Na versão limitada 3.13 da API C, a função Py_SET_REFCNT() agora é implementada como uma chamada de função opaca. Patch por Victor Stinner.

  • gh-108082: Adiciona a função PyErr_FormatUnraisable().

  • gh-110964: Move as funções privadas não documentadas _PyArg e a estrutura _PyArg_Parser para a API C interna (pycore_modsupport.h). Patch por Victor Stinner.

  • gh-110815: Suporte a nomes de palavras reservadas não ASCII em PyArg_ParseTupleAndKeywords().

  • gh-109587: Introduzida PyUnstable_PerfTrampoline_CompileCode(), PyUnstable_PerfTrampoline_SetPersistAfterFork() e PyUnstable_CopyPerfMapFile(). Essas funções permitem que módulos de extensão inicializem trampolins avidamente, depois que o aplicativo é “aquecido”. Isso torna possível ter perf-trampolines em execução de forma sempre habilitada.

  • gh-85283: Adiciona a função PySys_Audit() à API C limitada. Patch por Victor Stinner.

  • gh-85283: Adiciona PyMem_RawMalloc(), PyMem_RawCalloc(), PyMem_RawRealloc() e PyMem_RawFree() à API C limitada. Patch por Victor Stinner.

  • gh-106672: Funções PyDict_GetItem(), PyDict_GetItemString(), PyMapping_HasKey(), PyMapping_HasKeyString(), PyObject_HasAttr(), PyObject_HasAttrString() e PySys_GetObject(), que limpam todos os erros ocorridos durante a chamada da função, agora os relatam usando sys.unraisablehook().

  • gh-67565: Remove a verificação redundante de contiguidade C em getargs.c, binascii, ssl e Clínica de Argumentos. Remendado por Stefan Krah e Furkan Onder

Python 3.13.0 alpha 1

Data de lançamento: 2023-10-13

Segurança

  • gh-108310: Corrigido um problema em que instâncias de ssl.SSLSocket eram vulneráveis a um desvio do handshake TLS e incluíam proteções (como verificação de certificado) e tratavam dados não criptografados enviados como se fossem dados criptografados TLS pós-handshake. Problema de segurança relatado como CVE 2023-40217 por Aapo Oksman. Patch por Gregory P. Smith.

  • gh-107774: PEP 669 especifica que sys.monitoring.register_callback gerará um evento de auditoria. Pré-lançamentos do Python 3.12 não geravam o evento de auditoria. Isso agora foi corrigido.

  • gh-102988: Revertida a alteração de melhoria de segurança email.utils lançada na 3.12beta4 que involuntariamente fez com que email.utils.getaddresses falhasse ao analisar endereços de e-mail com uma vírgula no campo de nome entre aspas. Veja gh-106669.

  • gh-99108: Atualiza nosso novo código HACL* embutido hashlib do upstream. O SHA2 embutido deve ser mais rápido e um problema com SHA3 em plataformas de 32 bits foi corrigido.

  • gh-102509: Começa a inicializar ob_digit durante a criação de objetos PyLongObject. Patch por Illia Volochii.

Núcleo e embutidos

  • gh-110782: Corrige o travamento quando typing.TypeVar é construído com um argumento nomeado. Patch por Jelle Zijlstra.

  • gh-110752: Redefine ceval.eval_breaker em interpreter_clear()

  • gh-110721: Usa a implementação de traceback para a funcionalidade padrão PyErr_Display(). Patch por Pablo Galindo

  • gh-110696: Corrige mensagem de erro incorreta para descompactação de argumento inválido. Patch por Pablo Galindo

  • gh-104169: Divide o tokenizador em dois diretórios separados: - Uma parte inclui a lógica de produção do lexema real e fica em Parser/lexer. - A segunda parte encapsula o lexer de acordo com os diferentes modos de tokenização que temos (string, utf-8, file, interactive, readline) e fica em Parser/tokenizer.

  • gh-110688: Remove o método não documentado test_c_api de set, que foi definido apenas para fins de teste em Py_DEBUG. Agora temos testes CAPI adequados.

  • gh-104584: Corrige um vazamento de referência ao executar com PYTHONUOPS ou -X uops habilitado.

  • gh-110514: Adiciona PY_THROW para eventos sys.setprofile()

  • gh-110489: Otimiza math.ceil() quando a entrada for exatamente um float, resultando em uma melhoria de cerca de 10%.

  • gh-110455: Guard assert(tstate->thread_id > 0) with #ifndef HAVE_PTHREAD_STUBS. This allows for pydebug builds to work under WASI which (currently) lacks thread support.

  • gh-110309: Remove nós constantes vazios desnecessários no final das especificações da f-strings.

  • gh-110259: Identifica corretamente a especificação de formato em f-strings (com aspas simples ou triplas) que tenham várias linhas na parte da expressão e incluam uma especificação de formatação. Patch por Pablo Galindo

  • gh-110237: Corrige verificações de erro ausentes para chamadas para PyList_Append em _PyEval_MatchClass.

  • gh-110164: regrtest: Se a variável de ambiente SOURCE_DATE_EPOCH for definida, o regrtest agora desabilita a aleatorização de testes. Patch por Victor Stinner.

  • gh-109889: Corrige o algoritmo de detecção de NOP redundante do compilador para ignorar NOPs sem número de linha ao procurar o número de linha da próxima instrução.

  • gh-109853: sys.path[0] agora está definido corretamente para subinterpretadores.

  • gh-109923: Define o número da linha no POP_TOP que segue um RETURN_GENERATOR.

  • gh-105716: Subinterpretadores agora lidam corretamente com o caso em que eles têm threads em execução em segundo plano. Antes, tais threads interferiam na limpeza e destruição delas, assim como impediam a execução de outro script.

  • gh-109369: O eval_breaker interno e os sinalizadores de suporte, além da versão de monitoramento, foram mesclados em um único inteiro atômico para acelerar as verificações.

  • gh-109823: Corrige bug em que o compilador não ajusta rótulos ao remover um bloco básico vazio que é um alvo de salto.

  • gh-109793: O thread principal não sai mais prematuramente quando um subinterpretador é limpo durante a finalização do tempo de execução. O bug era um problema particularmente porque, quando acionado, o processo Python sempre retornava com um exitcode 0, mesmo se falhasse.

  • gh-109719: Corrige rótulos de alvos de salto ausentes quando o compilador reordena blocos frios/quentes.

  • gh-109595: Adiciona a opção de linha de comando -X cpu_count para substituir os resultados de retorno de os.cpu_count() e os.process_cpu_count(). Esta opção é útil para usuários que precisam limitar os recursos da CPU de um sistema de contêiner sem ter que modificar o contêiner (código da aplicação). Patch por Donghee Na.

  • gh-109627: Corrige bug em que o compilador não atribui um novo rótulo de alvo de salto a um pequeno bloco de saída duplicado.

  • gh-109596: Corrige alguns tokens na gramática que estavam marcados incorretamente como palavras-chave suaves. Corrigir também alguns nomes de regras repetidos e garantir que regras repetidas não sejam permitidas. Patch por Pablo Galindo.

  • gh-109496: Em um Python construído em modo de depuração, Py_DECREF() agora chama _Py_NegativeRefcount() se o objeto for um ponteiro pendente para memória desalocada: memória preenchida com 0xDD “byte morto” pelo gancho de depuração nos alocadores de memória. A correção consiste em verificar a contagem de referências antes de verificar _Py_IsImmortal(). Patch por Victor Stinner.

  • gh-107265: Faz deopt de opcodes ocultos pelo executor quando o opcode base é necessário

  • gh-109371: Feito deopt corretamente nas instruções para inicialização de ferramenta e modificada a asserção incorreta na instrumentação, quando uma ferramenta anterior já define eventos INSTRUCTION

  • gh-105658: Corrige bug em que o rastreamento de linha de um bloco except terminando com uma condicional inclui um evento em excesso com a linha da expressão condicional.

  • gh-109219: Corrige escopos de parâmetros de tipo de compilação que usam um nome que também é livre em um escopo interno.

  • gh-109351: Corrige falha ao compilar um AST inválido envolvendo uma expressão nomeada (morsa).

  • gh-109341: Corrige falha ao compilar um AST inválido envolvendo um ast.TypeAlias.

  • gh-109195: Corrige o local de origem para a instrução LOAD_* que precede um LOAD_SUPER_ATTR para carregar a variável global super (ou variável de sombreamento) para que ela abranja apenas o nome super e não os parênteses seguintes.

  • gh-109256: Os IDs de opcode para opcodes especializados são alocados em seu próprio intervalo para melhorar a estabilidade dos IDs para os opcodes ‘reais’.

  • gh-109216: Corrige possível vazamento de memória em BUILD_MAP.

  • gh-109207: Corrige um SystemError em __repr__ do objeto de entrada da tabela de símbolos.

  • gh-109179: Corrige bug em que a exibição do traceback C descarta notas de SyntaxError.

  • gh-109118: Não permitir escopos aninhados (lambdas, expressões geradoras e compreensões) dentro de escopos de anotação PEP 695 que estejam aninhados dentro de classes.

  • gh-109156: Adiciona testes para instruções de desinstrumentação, mantendo a instrumentação para linhas

  • gh-109114: Relaxa a detecção da mensagem de erro para lambdas inválidas dentro de f-strings para não procurar campos de substituição arbitrários e evitar falsos positivos. Patch por Pablo Galindo

  • gh-105848: Adiciona um novo opcode CALL_KW, usado para chamadas que contêm argumentos nomeados. Além disso, corrige uma possível falha ao pular chamadas de método em um depurador.

  • gh-109052: Use o opcode base ao comparar objetos de código para evitar interferência da instrumentação

  • gh-109118: Corrige falha do interpretador quando uma exceção NameError é levantada dentro dos parâmetros de tipo de uma classe genérica.

  • gh-88943: Melhora o erro de sintaxe para caracteres não ASCII que seguem um literal numérico. Agora, ele aponta para o caractere não ASCII inválido, não para o literal numérico válido.

  • gh-108976: Corrige falha que ocorre após desinstrumentar um objeto código em uma função de retorno de monitoramento.

  • gh-108732: Torna as variáveis de iteração de compreensões de escopo de módulo e classe visíveis para pdb e outras ferramentas que usam frame.f_locals novamente.

  • gh-108959: Corrigir o posicionamento do cursor para locais de erro em operações binárias e de subscrito que envolvem parênteses e espaços não semânticos. Patch por Pablo Galindo.

  • gh-104584: Corrige uma falha ao executar com PYTHONUOPS ou -X uops habilitado e ocorre um erro durante a otimização.

  • gh-108727: Define tp_dealloc para CounterOptimizer_Type. Isso corrige uma falha de segmentação na desalocação.

  • gh-108520: Corrige multiprocessing.synchronize.SemLock.__setstate__() para inicializar corretamente multiprocessing.synchronize.SemLock._is_fork_ctx. Isso corrige uma regressão ao passar um SemLock entre processos aninhados.

    Renomeia multiprocessing.synchronize.SemLock.is_fork_ctx para multiprocessing.synchronize.SemLock._is_fork_ctx para evitar expô-lo como API pública.

  • gh-108654: Restaura os locais sombreados por uma compreensão embutida se a compreensão levantar uma exceção.

  • gh-108488: Altera a inicialização das entradas de cache em linha para que a entrada de cache para JUMP_BACKWARD seja inicializada com zero, em vez do valor adaptive_counter_warmup() usado para todas as outras instruções. Este contador, único entre as instruções, conta a partir de zero.

  • gh-108716: Desativa o congelamento profundo de objetos código. Os módulos permanecem congelados, de modo que não é necessária uma pesquisa no sistema de arquivos para módulos comuns.

  • gh-108614: Adiciona a instrução RESUME_CHECK para evitar ter que manipular instrumentação, sinais e alternância de contextos no mecanismo de execução de nível 2.

  • gh-108487: Move um assert que causaria uma falha espúria em um caso tortuoso que deveria apenas acionar a desotimização.

  • gh-106176: Usa um WeakValueDictionary para rastrear as listas que contêm os módulos que cada thread está importando no momento. Isso ajuda a evitar um vazamento de referência, que mantém a lista ativa por mais tempo do que o necessário. Referências fracas são usadas, pois o GC não pode interromper a limpeza.

  • gh-105481: O estágio de construção regen-opcode foi removido e seu trabalho agora é feito em regen-cases.

  • gh-107901: Corrige número de linha ausente em JUMP_BACKWARD no final de um laço for.

  • gh-108113: A função embutida compile() agora pode aceitar um novo sinalizador, ast.PyCF_OPTIMIZED_AST, que é semelhante a ast.PyCF_ONLY_AST exceto que o AST retornado é otimizado de acordo com o valor do argumento optimize.

    ast.parse() agora aceita um argumento opcional optimize que é passado para o compile() embutido. Isto torna possível obter um AST otimizado.

  • gh-107971: Os IDs de opcode são gerados a partir de bytecodes.c em vez de serem codificados em opcode.py.

  • gh-107944: Melhora a mensagem de erro para chamadas de função com argumentos nomeados inválidos. Patch por Pablo Galindo.

  • gh-108390: Levanta uma exceção ao definir um evento não local (RAISE, EXCEPTION_HANDLED, etc.) em sys.monitoring.set_local_events.

    Corrige travamento ao rastrear chamadas recursivas para classes Python.

  • gh-108035: Remove a estrutura _PyCFrame, movendo o ponteiro para o quadro do interpretador atual de volta ao estado da thread, como era na versão 3.10 e anteriores. O _PyCFrame existia como uma otimização de desempenho para rastreamento. Desde que a PEP 669 foi implementada, essa otimização não se aplica mais.

  • gh-91051: Corrige abort/segfault ao usar todos os oito slots do observador de tipo, em plataformas onde char tem sinal por padrão.

  • gh-106581: Corrige possíveis falhas de asserção e eventos de instrumentação ausentes quando PYTHONUOPS ou -X uops estiver habilitado.

  • gh-107526: Reverte a conversão de vars, dir, next, getattr e iter para clínica de argumentos.

  • gh-84805: Gera assinatura automaticamente para funções de extensão METH_NOARGS e METH_O.

  • gh-107758: Torna a rotina dump_stack() usada pelo recurso lltrace (depuração de interpretador de baixo nível) robusta contra recursão, garantindo que ela nunca chame um método __repr__ implementado em Python. Além disso, faça com que a saída semelhante para UOPs de Nível 2 apareça em stdout (em vez de stderr), para corresponder ao código lltrace em ceval.c.

  • gh-107659: Adiciona docstrings para ctypes.pointer() e ctypes.POINTER().

  • gh-105848: Modifica o bytecode para que o chamável real para um CALL esteja em uma posição consistente na pilha (independentemente de as otimizações de chamada de método vinculado estarem ativas ou não).

  • gh-107674: Regressão de desempenho corrigida em sys.settrace.

  • gh-107724: Nas versões de pré-lançamento da 3.12, até a rc1, a função de retorno de chamada sys.monitoring para o evento PY_THROW não continha o terceiro argumento, exception. Isso já foi corrigido.

  • gh-84436: Ignora modificações na contagem de referências para muitos objetos imortais conhecidos.

  • gh-107596: Especializa a subscrição de objetos str por índices int.

  • gh-107080: As construções de referências de rastreamento (--with-trace-refs) estavam travando quando usadas com subinterpretadores isolados. O estado global problemático foi isolado para cada interpretador. Além de corrigir as falhas, essa alteração não afeta os usuários.

  • gh-107557: Gera os casos necessários para o interpretador abstrato barebones de nível 2 para passagens de otimização em CPython.

  • gh-106608: Torna _PyUOpExecutorObject de comprimento variável.

  • gh-100964: Limpa o estado de exceção dos geradores após return para interromper os ciclos de referência.

  • gh-107455: Melhora as mensagens de erro ao converter um tipo incompatível para ctypes.c_char_p, ctypes.c_wchar_p e ctypes.c_void_p.

  • gh-107263: Aumenta o limite de recursão em C para funções que não sejam o interpretador principal de 800 para 1500. Isso deve permitir que funções como list.__repr__ e json.dumps manipulem todas as entradas possíveis antes da versão 3.12.

  • gh-104584: Corrige um problema que causava a leitura incorreta de caches inline ao executar com PYTHONUOPS ou -X uops habilitados.

  • gh-104432: Corrige possível acesso desalinhado à memória em APIs C envolvendo sequências retornadas de ponteiros char * dentro dos módulos grp e socket. Isso foi revelado usando uma compilação -fsaniziter=alignment no macOS ARM. Patch por Christopher Chavez.

  • gh-106078: Isola _decimal (aplicar PEP 687). Patch por Charlie Zhao.

  • gh-106898: Adiciona a exceção como terceiro argumento às funções de retorno PY_UNIND em sys.monitoring. Isso torna o callback PY_UNWIND consistente com as outras funções de retorno de tratamento de exceções.

  • gh-106895: Levanta um ValueError quando uma função de callback de monitoramento retornar DISABLE para eventos que não podem ser desabilitados localmente.

  • gh-106897: Adiciona um evento RERAISE a sys.monitoring, que ocorre quando uma exceção é reativada, seja explicitamente por uma instrução raise simples ou implicitamente em um bloco except ou finally.

  • gh-77377: Garante que objetos de sincronização multiprocessamento criados em um contexto de fork não sejam enviados para um processo diferente criado em um contexto de geração. Isso transforma um erro de segmentação em um erro de tempo de execução acionável no processo pai.

  • gh-106931: Objetos string alocados estaticamente agora são internados globalmente em vez de por interpretador. Isso corrige uma situação em que tal string só seria internada em um único interpretador. Objetos string normais não são afetados.

  • gh-104621: Módulos não suportados agora sempre falham na importação.

  • gh-107122: Adicionado dbm.ndbm.ndbm.clear() a dbm.ndbm. Patch por Donghee Na.

  • gh-107122: Adiciona dbm.gnu.gdbm.clear() a dbm.gnu. Patch por Donghee Na.

  • gh-107015: Os tokens ASYNC e AWAIT foram removidos da gramática, o que elimina a possibilidade de criar as palavras reservadas contextuais async e await ao usar feature_version<7 em ast.parse().

  • gh-106917: Corrige chamadas ao método super() no estilo classmethod (ou seja, onde o segundo argumento para super(), ou o segundo argumento implícito extraído de self/cls no caso de super com argumento zero, é um tipo) quando o alvo da chamada não é um classmethod.

  • gh-105699: O Python não trava mais devido a uma corrida pouco frequente ao inicializar strings internas por interpretador. A falha se manifestava quando o interpretador era finalizado.

  • gh-105699: O Python não trava mais devido a uma corrida pouco frequente na configuração de Py_FileSystemDefaultEncoding e Py_FileSystemDefaultEncodeErrors (ambos descontinuados), ao inicializar simultaneamente dois subinterpretadores isolados. Agora, eles são definidos apenas durante a inicialização em tempo de execução.

  • gh-106908: Corrige vários travamentos, vazamentos de referência, falhas de teste e bugs de rastreamento/introspecção ao executar com PYTHONUOPS ou -X uops habilitado.

  • gh-106092: Corrige uma falha de segmentação causada por um bug de uso após liberação em frame_dealloc quando a lixeira atrasa a desalocação de um PyFrameObject.

  • gh-106485: Reduz o número de dicionários de instâncias materializadas, desmaterializando-os quando possível.

  • gh-106719: Não suprime mais erros arbitrários nos getters e setters __annotations__ nos tipos type e module.

  • gh-106723: Propaga frozen_modules para interpretadores de processos gerados por multiprocessamento.

  • gh-104909: Divide LOAD_ATTR_INSTANCE_VALUE em micro-ops.

  • gh-104909: Divide as especializações LOAD_GLOBAL em micro-ops.

  • gh-106597: Uma nova estrutura de depuração de offsets foi adicionada ao _PyRuntimeState que ajudará depuradores e profilers fora do processo a obter as posições para estruturas relevantes do interpretador de uma forma independente de como o Python foi compilado e que não exija a cópia dos cabeçalhos. Patch por Pablo Galindo

  • gh-106487: Permite que o argumento count de str.replace() seja nomeado. Patch por Hugo van Kemenade.

  • gh-96844: Melhora a mensagem de erro de list.remove(). Patch por Donghee Na.

  • gh-81283: O compilador agora remove recuos de docstrings. Reduz o tamanho do arquivo pyc em 5% quando o módulo é amplamente documentado. Essa alteração afeta __doc__, portanto, ferramentas como doctest serão afetadas.

  • gh-106396: Quando a especificação de formato de uma expressão de f-string está vazia, o analisador agora gera um nó ast.JoinedStr vazio para ela, em vez de um nó ast.JoinedStr de um elemento com uma string vazia ast.Constant.

  • gh-100288: Especializa LOAD_ATTR para não descritores na classe. Adiciona LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES e LOAD_ATTR_NONDESCRIPTOR_NO_DICT.

  • gh-106008: Corrige possíveis vazamentos de referência ao não otimizar comparações com None no compilador de bytecode.

  • gh-106145: Torna end_lineno e end_col_offset obrigatórios em nós AST type_param.

  • gh-106213: Alterada a forma como os trampolins de chamada do Emscripten funcionam para compatibilidade com a integração Wasm/JS Promise.

  • gh-106182: sys.getfilesystemencoding() e sys.getfilesystemencodeerrors agora retornam objetos Unicode internalizados.

  • gh-106210: Removido o trampolim de importação do Emscripten, pois não era mais necessário para o Pyodide.

  • gh-104584: Adicionado um novo otimizador e interpretador de rastreamento experimental (também conhecido como “nível 2”). Atualmente, isso é pessimista, então não use ainda — esta é uma infraestrutura para que possamos experimentar com passes de otimização. Para habilitá-lo, passe -Xuops ou defina PYTHONUOPS=1. Para obter a saída de depuração, defina PYTHONUOPSDEBUG=N, onde N é um nível de depuração (0-4, onde 0 indica ausência de saída de depuração e 4 indica excesso de verbosidade).

  • gh-105775: LOAD_CLOSURE agora é uma pseudo-op.

  • gh-105730: Permite qualquer chamada que não seja de objetos de tipo como predicado de condição em BaseExceptionGroup.split() e BaseExceptionGroup.subgroup().

  • gh-105979: Corrige falha em _imp.get_frozen_object() devido a tratamento incorreto de exceções.

  • gh-106003: Adiciona uma nova instrução TO_BOOL, que realiza conversões booleanas para POP_JUMP_IF_TRUE, POP_JUMP_IF_FALSE e UNARY_NOT (que agora esperam valores bool exatos). Além disso, modifique o oparg de COMPARE_OP para incluir um sinalizador opcional de “conversão booleana”.

  • gh-98931: Garante que mensagens de erro personalizadas SyntaxError sejam levantadas para importações inválidas com múltiplos destinos. Patch por Pablo Galindo

  • gh-105724: Melhora as mensagens de erro assert fornecendo o intervalo exato de erro.

  • gh-105908: Corrige o bug em que gh-99111 quebrava a importação futura barry_as_FLUFL no REPL do Python.

  • gh-105840: Corrige possíveis travamentos ao especializar chamadas de função com muitos __defaults__.

  • gh-105831: Corrige um bug em uma f-string, onde o uso de uma expressão de depuração (o sinal =) que aparece na última linha de um arquivo resulta no buffer de depuração que contém o texto da expressão sendo um caractere a menos.

  • gh-105800: Emite corretamente SyntaxWarning em f-strings se sequências inválidas forem usadas. Patch por Pablo Galindo

  • gh-105340: Inclui a variável de iteração de compreensão em locals() dentro de uma compreensão de escopo de módulo ou classe.

  • gh-105331: Levanta ValueError se o argumento delay para asyncio.sleep() for um NaN (correspondente a time.sleep()).

  • gh-105587: O tempo de execução não pode garantir que objetos imortais não serão mutados por extensões. Portanto, isso modifica _PyStaticObject_CheckRefcnt para avisar em vez de declarar.

  • gh-105564: Não inclui quebras de linha artificiais no atributo line de tokens nas APIs do módulo tokenize. Patch por Pablo Galindo

  • gh-105549: Tokeniza separadamente os tokens NUMBER e NAME que não sejam ambíguos. Patch por Pablo Galindo.

  • gh-105588: Corrige um problema que poderia resultar em travamentos ao compilar nós ast malformados.

  • gh-100987: Permite objetos que não são objetos código como o “executável” em quadros internos. A longo prazo, isso pode ajudar ferramentas como Cython e PySpy a interagirem de forma mais eficiente. A curto prazo, nos permite realizar algumas otimizações de forma mais simples.

  • gh-105375: Corrige bugs no módulo builtins, onde exceções poderiam ser sobrescritas.

  • gh-105375: Corrige bug no compilador, onde uma exceção poderia ser sobrescrita.

  • gh-105375: Melhora o tratamento de erros em PyUnicode_BuildEncodingMap(), onde uma exceção poderia ser sobrescrita.

  • gh-105486: Altera a representação da lista de argumentos ParamSpec em types.GenericAlias.

  • gh-105678: Divide a instrução MAKE_FUNCTION em duas partes: MAKE_FUNCTION, que cria a função, e SET_FUNCTION_ATTRIBUTE, que define os atributos da função. Isso torna o efeito de pilha de MAKE_FUNCTION regular para facilitar a otimização e a geração de código.

  • gh-105435: Corrige o caractere de quebra de linha falso se o arquivo terminar em um comentário sem quebra de linha. Patch por Pablo Galindo

  • gh-105390: Levanta corretamente as exceções tokenize.TokenError em vez de SyntaxError para erros de tokenização, como entrada incompleta. Patch por Pablo Galindo

  • gh-105259: Não inclui o caractere de quebra de linha para tokens NEWLINE finais emitidos no módulo tokenize. Patch por Pablo Galindo

  • gh-104635: Elimina instruções redundantes STORE_FAST no compilador. Patch por Donghee Na e Carl Meyer.

  • gh-105324: Corrige a função principal do módulo tokenize ao ler de sys.stdin. Patch por Pablo Galindo

  • gh-33092: Simplifica e acelera o interpretador para f-strings. Remove o opcode FORMAT_VALUE. Adiciona opcodes CONVERT_VALUE, FORMAT_SIMPLE e FORMAT_WITH_SPEC. O compilador emite uma sequência mais eficiente para cada expressão de formato.

  • gh-105229: Remove as superinstruções restantes de duas unidades de código. Todas as superinstruções restantes usam apenas uma unidade de código, simplificando a instrumentação e agilizando o processamento.

  • gh-105235: Impede o acesso à memória fora dos limites durante chamadas mmap.find().

  • gh-98963: Restaura a capacidade de uma subclasse de property definir __slots__ ou, de outra forma, ser livre de dicionários, ignorando falhas na definição de uma docstring em tal classe. Esse comportamento havia regredido na versão 3.12beta1. Um AttributeError onde não havia um anteriormente era prejudicial ao código existente.

  • gh-104812: O mecanismo de “chamada pendente” agora funciona para todos os interpretadores, não apenas para o interpretador principal, e é executado em todas as threads, não apenas na thread principal. Algumas chamadas ainda são feitas apenas na thread principal, ou seja, no interpretador principal. Esta alteração não afeta o tratamento de sinais nem a C-API pública existente (Py_AddPendingCall()), que ainda têm como alvo apenas a thread principal. A nova funcionalidade destina-se estritamente ao uso interno por enquanto, uma vez que as consequências de seu uso ainda não são bem compreendidas, exceto em alguns casos muito restritos. Esta alteração alinha a capacidade com a intenção quando o estado foi definido por interpretador há vários anos.

  • gh-105194: Não escapa com barras invertidas os especificadores de formato de f-string. Patch por Pablo Galindo

  • gh-105229: Substitui algumas superinstruções dinâmicas por equivalentes de instrução única.

  • gh-105162: Corrigido bug em generator.close()/throw(), onde um iterador interno era ignorado quando o iterador externo era instrumentado.

  • gh-105164: Garante que as anotações sejam configuradas corretamente se a única anotação em um bloco estiver dentro de um bloco match. Patch por Jelle Zijlstra.

  • gh-105148: Torna _PyASTOptimizeState interno a ast_opt.c. Torna _PyAST_Optimize com dois inteiros em vez de um ponteiro para esta estrutura. Isso evita a necessidade de incluir pycore_compile.h em ast_opt.c.

  • gh-104799: Atributos de nós ast que são listas agora assumem como padrão a lista vazia se omitidos. Isso significa que alguns códigos que anteriormente geravam TypeError quando o nó AST era usado agora prosseguirão com a lista vazia. Patch por Jelle Zijlstra.

  • gh-105111: Remove as antigas macros da lixeira Py_TRASHCAN_SAFE_BEGIN e Py_TRASHCAN_SAFE_END. Elas devem ser substituídas pelas novas macros Py_TRASHCAN_BEGIN e Py_TRASHCAN_END.

  • gh-105035: Corrige chamadas de super() em tipos com implementação personalizada de tp_getattro (por exemplo, metatipos).

  • gh-105017: Exibe linhas CRLF no atributo de string tokenize em tokens NL e NEWLINE. Patch por Marta Gómez.

  • gh-105013: Corrige o tratamento de lambdas entre parênteses de várias linhas em inspect.getsource(). Patch por Pablo Galindo

  • gh-105017: Não inclui um token final NL adicional ao analisar arquivos com linhas CRLF. Patch por Marta Gómez.

  • gh-104976: Garante que os objetos tokenize.TokenInfo DEDENT finais emitidos pelo módulo tokenize sejam reportados como no Python 3.11. Patch por Pablo Galindo.

  • gh-104972: Garante que o atributo line em objetos tokenize.TokenInfo no módulo tokenize estejam sempre corretos. Patch por Pablo Galindo

  • gh-104955: Corrige a assinatura para o novo slot de __release_buffer__(). Patch por Jelle Zijlstra.

  • gh-104690: Iniciar novas threads e criar processos através de os.fork() durante o desligamento do interpretador (como a partir de manipuladores atexit) não é mais suportado. Isso pode levar a uma condição de corrida entre a thread principal do tempo de execução do Python, liberando estados de threads enquanto rotinas internas de threading tentam alocar e usar o estado de threads recém-criadas. Ou filhos do fork tentando usar o tempo de execução e o estado da thread no meio do desligamento no processo filho.

  • gh-104879: Corrige a falha ao acessar o atributo __module__ de apelidos de tipo definidos fora de um módulo. Patch por Jelle Zijlstra.

  • gh-104825: Tokens emitidos pelo módulo tokenize não incluem mais um caractere \\n implícito no atributo line. Patch por Pablo Galindo

  • gh-104770: Se um gerador retornar um valor ao ser fechado, o valor agora é retornado por generator.close().

  • gh-89091: Levanta RuntimeWarning para métodos de gerador assíncronos não aguardados, como asend(), athrow() e aclose(). Patch por Kumar Aditya.

  • gh-96663: Adiciona uma mensagem de erro melhor e mais introspectiva ao definir atributos em classes sem um __dict__ e sem membro de slot para o atributo.

  • gh-93627: Atualiza a implementação do módulo pickle em Python para corresponder à implementação em C do módulo pickle. Para objetos que definem métodos de redução como __reduce_ex__() ou __reduce__() como None, a operação de pickle resultará em um TypeError.

  • gh-101006: Melhora o tratamento de erros ao ler dados marshal.

  • gh-91095: Especializa chamadas para a maioria das classes Python. Especificamente, qualquer classe que herde de object ou de outra classe Python e não sobrescreva __new__.

    A instrução especializada faz o seguinte:

    1. Cria o objeto (chamando object.__new__)

    2. Envia um quadro de correção para a pilha de quadros (para limpeza após __init__)

    3. Envia o quadro de __init__ para a pilha de quadros

    Acelera a instanciação da maioria das classes Python.

Biblioteca

  • gh-110786: A CLI de sysconfig agora ignora BrokenPipeError, fazendo com que ele saia normalmente se sua saída estiver sendo canalizada e o canal for fechado.

  • gh-103480: O módulo sysconfig agora é um pacote, em vez de um módulo de arquivo único.

  • gh-110733: Microotimização: Evite chamar min(), max() em BaseEventLoop._run_once().

  • gh-94597: Adicionado asyncio.EventLoop para uso com o kwarg asyncio.run() loop_factory para evitar chamar o sistema de políticas asyncio.

  • gh-110682: protocolos runtime-checkable usados para considerar __match_args__ um membro do protocolo em __instancecheck__ se estivesse presente no protocolo. Agora, este atributo é ignorado se estiver presente.

  • gh-110488: Corrige alguns problemas em pathlib.PurePath.with_name(): um único ponto era considerado incorretamente um nome válido e, em PureWindowsPath, um nome com um fluxo de dados NTFS alternativo, como a:b, era considerado incorretamente inválido.

  • gh-110590: Corrige um bug em _sre.compile(), onde TypeError era substituído por OverflowError quando o argumento code era uma lista de não-ints.

  • gh-65052: Impede que pdb trave ao tentar exibir objetos não exibíveis

  • gh-110519: Aviso de descontinuação sobre números não inteiros em gettext agora sempre se refere à linha no código do usuário onde a função ou método gettext é usado. Anteriormente, ele podia se referir a uma linha no código gettext.

  • gh-89902: Descontinua o especificador de formato não padrão “N” para decimal.Decimal. Ele não foi documentado e suportado apenas na implementação em C.

  • gh-110378: Os gerenciadores de contexto contextmanager() e asynccontextmanager() agora fecham um objeto gerador subjacente inválido que produz mais de um valor.

  • gh-106670: Em pdb, defina a variável de conveniência $_exception para depuração post mortem.

  • gh-110365: Corrige o bug em termios.tcsetattr() que estava sobrescrevendo erros existentes durante a análise de inteiros da lista term.

  • gh-109653: Melhora ligeiramente o tempo de importação de vários módulos da biblioteca padrão, adiando as importações de warnings dentro desses módulos. Patch por Alex Waygood.

  • gh-110273: dataclasses.replace() agora levanta TypeError em vez de ValueError se especificar o argumento nomeado para um campo declarado com init=False ou se o argumento nomeado não for especificado para o campo InitVar obrigatório.

  • gh-110249: Adiciona o sinalizador --inline-caches à linha de comando dis.

  • gh-109653: Corrige uma regressão do Python 3.12 no tempo de importação de random. Patch por Alex Waygood.

  • gh-110222: Adiciona suporte a objetos sequência struct em copy.replace(). Patch por Xuehai Pan.

  • gh-109649: multiprocessing, concurrent.futures, compileall: Substitui os.cpu_count() por os.process_cpu_count() para selecionar o número padrão de threads e processos de trabalho. Obter a afinidade da CPU, se compatível. Patch por Victor Stinner.

  • gh-110150: Corrige o tratamento de caso base em statistics.quantiles. Agora permite um único ponto de dados.

  • gh-110036: No Windows, o multiprocessamento Popen.terminate() agora captura PermissionError e obtém o código de saída do processo. Se o processo ainda estiver em execução, lança novamente o PermissionError. Caso contrário, o processo é encerrado conforme o esperado: armazena seu código de saída. Patch por Victor Stinner.

  • gh-110038: Corrige um problema que fazia com que KqueueSelector.select() não retornasse todos os eventos de prontidão em alguns casos quando um descritor de arquivo é registrado para leitura e escrita.

  • gh-110045: Atualiza o módulo symtable para suportar os novos escopos introduzidos por PEP 695.

  • gh-88402: Adiciona novas variáveis a sysconfig.get_config_vars() no Windows: LIBRARY, LDLIBRARY, LIBDIR, SOABI e Py_NOGIL.

  • gh-109631: Funções do re como re.findall(), re.split(), re.search() e re.sub(), que realizam correspondências curtas e repetidas, agora podem ser interrompidas pelo usuário.

  • gh-109653: Reduz o tempo de importação de email.utils em cerca de 43%. Isso resulta em uma redução de cerca de 18% no tempo de importação de email.message, o que, por sua vez, reduz o tempo de importação de importlib.metadata em cerca de 6%. Patch por Alex Waygood.

  • gh-109818: Corrige reprlib.recursive_repr() que não copiava __type_params__ da função decorada.

  • gh-109047: concurrent.futures: A thread do gerenciador de executores agora captura exceções ao adicionar um item à fila de chamadas. Durante a finalização do Python, a criação de uma nova thread agora pode gerar RuntimeError. Captura a chamada à exceção terminate_broken() neste caso. Patch por Victor Stinner.

  • gh-109782: Garante que a assinatura de os.path.isdir() seja idêntica em todas as plataformas. Patch por Amin Alaee.

  • gh-109653: Melhora o tempo de importação de functools em cerca de 13%. Patch por Alex Waygood.

  • gh-109590: shutil.which() dará preferência a arquivos com a extensão PATHEXT se o modo fornecido incluir os.X_OK no Win32. Se nenhuma correspondência com PATHEXT for encontrada, um arquivo sem a extensão PATHEXT poderá ser retornado. Esta alteração fará com que shutil.which() aja de forma mais semelhante ao comportamento anterior no Python 3.11.

  • gh-109653: Reduz o tempo de importação de enum em mais de 50%. Patch por Alex Waygood.

  • gh-109593: Evita impasses em uma chamada reentrante para o rastreador de recursos de multiprocessamento. Tal chamada reentrante, embora improvável, pode ocorrer se uma passagem de GC invocar o finalizador para um objeto de multiprocessamento, como SemLock.

  • gh-109653: Reduz o tempo de importação de typing em cerca de um terço. Patch por Alex Waygood.

  • gh-109649: Adiciona a função os.process_cpu_count() para obter o número de CPUs lógicas utilizáveis pela thread de chamada do processo atual. Patch por Victor Stinner.

  • gh-74481: Adiciona constantes relacionadas a set_error_mode no módulo msvcrt na construção de depuração do Python.

  • gh-109613: Corrige os.stat() e os.DirEntry.stat(): verificar exceções. Anteriormente, no Python construído em modo de depuração, essas funções podiam disparar um erro fatal do Python (e abortar o processo) quando uma função era bem-sucedida com uma exceção definida. Patch por Victor Stinner.

  • gh-109599: Expõe o tipo de objetos PyCapsule como types.CapsuleType.

  • gh-109109: Agora você pode obter as cadeias de certificados TLS brutas de conexões TLS por meio dos métodos ssl.SSLSocket.get_verified_chain() e ssl.SSLSocket.get_unverified_chain().

    Contribuição de Mateusz Nowak.

  • gh-109559: Atualiza o banco de dados unicodedata para Unicode 15.1.0.

  • gh-109543: Remove a verificação desnecessária de hasattr() durante a criação de typing.TypedDict.

  • gh-109495: Remove __slots__ extras desnecessários na implementação em Python puro de datetime para reduzir o tamanho da memória, pois são definidos na superclasse. Patch por James Hilton-Balfe

  • gh-109461: logging: Usa um gerenciador de contexto para aquisição de travas.

  • gh-109096: http.server.CGIHTTPRequestHandler has been deprecated for removal in 3.15. Its design is old and the web world has long since moved beyond CGI.

  • gh-109409: Corrige o erro que permitia herdar uma classe de dados congelada de vários pais, alguns dos quais possivelmente não estavam congelados.

  • gh-109375: O comando pdb alias agora impede o registro de apelidos sem argumentos.

  • gh-109319: Descontinua o campo dis.HAVE_ARGUMENT em favor de dis.hasarg.

  • gh-107219: Uma condição de corrida foi corrigida em concurrent.futures. Quando um processo no pool de processos era encerrado abruptamente (enquanto o future estava em execução ou pendente), a conexão era encerrada. Se a fila de chamadas estiver bloqueada no envio de bytes para um processo de trabalho, o encerramento da conexão de escrita interrompe o envio, permitindo o fechamento da fila. Patch por Victor Stinner.

  • gh-66143: O objeto codecs.CodecInfo agora é copiável e pode ser selecionado. Patch por Robert Lehmann e Furkan Onder.

  • gh-109187: pathlib.Path.resolve() agora trata laços de links simbólicos como outros erros: no modo estrito, OSError é levantada, e no modo não estrito, nenhuma exceção é levantada.

  • gh-50644: Tenta serializar com pickle ou criar uma cópia rasa ou profunda de fluxos codecs agora levantam um TypeError. Anteriormente, a cópia falhava com um RecursionError, enquanto o pickle produzia resultados incorretos que eventualmente causavam a falha ao desserializar com pickle com um RecursionError.

  • gh-109174: Adicionado suporte a types.SimpleNamespace em copy.replace().

  • gh-109164: pdb: Substitui getopt por argparse para analisar argumentos de linha de comando.

  • gh-109151: Habilita os recursos de edição readline na interface de linha de comando sqlite3 (python -m sqlite3).

  • gh-108987: Corrige a condição de corrida _thread.start_new_thread(). Se uma thread for criada durante a finalização do Python, a thread recém-gerada agora sai imediatamente em vez de tentar acessar a memória liberada e causar um travamento. Patch por Victor Stinner.

  • gh-108682: Enum: requer names=() ou type=... para criar uma enumeração vazia usando a sintaxe funcional.

  • gh-109033: Exceções levantadas pela função embutida os.utime agora incluem o nome do arquivo relacionado.

  • gh-108843: Corrige um problema em ast.unparse() ao desfazer a análise de f-strings contendo muitos tipos de aspas.

  • gh-108469: ast.unparse() agora oferece suporte à nova sintaxe f-string introduzida no Python 3.12. Observe que as aspas f-string foram selecionadas novamente para simplificar a nova sintaxe. (Patch por Steven Sun)

  • gh-108751: Adiciona a função copy.replace(), que permite criar uma cópia modificada de um objeto. Ela oferece suporte às tuplas nomeadas, classes de dados e muitos outros objetos.

  • gh-108682: Enum: Levanta TypeError se super().__new__() for chamado de um __new__ personalizado.

  • gh-108278: Descontinua a passagem do retorno de chamada por argumento nomeado para as seguintes APIs sqlite3.Connection:

    Os parâmetros afetados se tornarão somente-posicionais no Python 3.15.

    Patch por Erlend E. Aasland.

  • gh-105829: Corrige impasse (deadlock) em concurrent.futures.ProcessPoolExecutor

  • gh-108295: Corrige travamentos relacionados ao uso de referências fracas em typing.TypeVar.

  • gh-108463: Faz com que expressões/instruções funcionem conforme o esperado no pdb

  • gh-108277: Adiciona os.timerfd_create(), os.timerfd_settime(), os.timerfd_gettime(), os.timerfd_settime_ns() e os.timerfd_gettime_ns() para fornecer uma interface de baixo nível para o descritor de arquivo de notificação de timer do Linux.

  • gh-107811: tarfile: a extração de membros com UID ou GID muito grande (por exemplo, em um sistema operacional com id_t de 32 bits) agora falha da mesma forma que a falha na definição do ID.

  • gh-64662: Corrige o suporte para tabelas virtuais em sqlite3.Connection.iterdump(). Patch por Aviv Palivoda.

  • gh-108111: Corrige uma regressão introduzida em gh-101251 para a versão 3.12, resultando em um cálculo de deslocamento incorreto em gzip.GzipFile.seek().

  • gh-108294: time.sleep() agora levanta um evento de auditoria.

  • gh-108278: Descontinua a passagem de nome, número de argumentos e o chamável como argumentos nomeados para as seguintes APIs de sqlite3.Connection:

    Os parâmetros afetados se tornarão somente-posicionais no Python 3.15.

    Patch por Erlend E. Aasland.

  • gh-108322: Aceleração de NormalDist.samples() usando o método CDF inverso em vez de chamar random.gauss().

  • gh-83417: Adiciona a capacidade do venv de criar um arquivo .gitignore, que faz com que o ambiente criado seja ignorado pelo Git. Essa configuração é ativada por padrão quando o venv é chamado por meio de sua CLI.

  • gh-105736: Harmonização da versão Python pura de OrderedDict com a versão C. Agora, ambas as versões configuram seu estado interno em __new__. Anteriormente, a versão Python pura fazia a configuração em __init__.

  • gh-108083: Corrige bugs no construtor de sqlite3.Connection e sqlite3.Connection.close(), onde exceções poderiam vazar. Patch por Erlend E. Aasland.

  • gh-107932: Corrige o módulo dis para relatar e exibir corretamente o bytecode que não possui linhas de código-fonte.

  • gh-105539: sqlite3 agora emite uma ResourceWarning se um objeto sqlite3.Connection não for fechado explicitamente. Patch por Erlend E. Aasland.

  • gh-107995: O atributo __module__ em instâncias de functools.cached_property agora é definido como o nome do módulo no qual a cached_property está definida, em vez de “functools”. Isso significa que os doctests em docstrings cached_property agora são coletados corretamente pelo módulo doctest. Patch por Tyler Smart.

  • gh-107963: Corrige multiprocessing.set_forkserver_preload() para verificar a lista de nomes de módulos fornecida. Patch por Donghee Na.

  • gh-106242: Corrige os.path.normpath() para manipular caracteres nulos incorporados sem truncar o caminho.

  • gh-81555: xml.dom.minidom agora coloca apenas aspas " em atributos.

  • gh-50002: xml.dom.minidom agora preserva espaços em branco em atributos.

  • gh-93057: Passa mais de um argumento posicional para sqlite3.connect() e o construtor sqlite3.Connection está obsoleto. Os parâmetros restantes se tornarão somente-nomeados no Python 3.15. Patch por Erlend E. Aasland.

  • gh-76913: Adiciona o parâmetro/recurso merge_extra a logging.LoggerAdapter

  • gh-107913: Corrige possíveis perdas dos valores errno e winerror em exceções OSError se eles fossem limpados ou modificados pelo código de limpeza antes de criar o objeto de exceção.

  • gh-107845: tarfile.data_filter() agora leva em consideração a localização dos links simbólicos ao determinar seu destino, portanto, não rejeitará mais alguns tarballs válidos com LinkOutsideDestinationError.

  • gh-107812: Estende o suporte a netlink do socket para a plataforma FreeBSD.

  • gh-107805: Corrige assinaturas de funções geradas em nível de módulo no turtle.

  • gh-107782: pydoc agora é capaz de exibir assinaturas que não são representáveis em Python, por exemplo, para getattr e dict.pop.

  • gh-56166: Descontinua a passagem de argumentos opcionais maxsplit, count e flags em funções de nível de módulo re.split(), re.sub() e re.subn() como posicionais. Eles devem ser passados apenas como nomeados.

  • gh-107710: Acelera logging.getHandlerNames().

  • gh-107715: Corrige doctest.DocTestFinder.find() na presença de nomes de classe com caracteres especiais. Patch por Gertjan van Zwieten.

  • gh-100814: Passa um objeto chamável como um valor de opção para uma imagem Tkinter agora levanta o TclError esperado em vez de um AttributeError.

  • gh-72684: Adiciona métodos de widget tkinter: tk_busy_hold(), tk_busy_configure(), tk_busy_cget(), tk_busy_forget(), tk_busy_current() e tk_busy_status().

  • gh-106684: Levanta ResourceWarning quando asyncio.StreamWriter não for fechado, causando vazamentos de memória. Patch por Kumar Aditya.

  • gh-107465: Adiciona método de classe pathlib.Path.from_uri().

  • gh-107077: Parece que em algumas condições, o OpenSSL retornará SSL_ERROR_SYSCALL em vez de SSL_ERROR_SSL quando uma verificação de certificação falhar, mas os parâmetros de erro ainda conterão ERR_LIB_SSL e SSL_R_CERTIFICATE_VERIFY_FAILED. Estamos detectando essa situação e levantando o erro ssl.SSLCertVerificationError apropriado. Patch por Pablo Galindo

  • gh-107576: Corrige types.get_original_bases() para retornar __orig_bases__ somente se estiver presente diretamente em cls. Patch por James Hilton-Balfe.

  • gh-105481: Remove opcode.is_pseudo, opcode.MIN_PSEUDO_OPCODE e opcode.MAX_PSEUDO_OPCODE, que foram adicionados na versão 3.12, nunca foram documentados e não foram projetados para uso externo.

  • gh-105481: opcode.ENABLE_SPECIALIZATION (que foi adicionado na versão 3.12, mas nunca foi documentado ou destinado ao uso externo) foi movido para _opcode.ENABLE_SPECIALIZATION, onde os testes podem acessá-lo.

  • gh-107396: tarfiles; Corrigido o uso antes da atribuição de self.exception para descompactação gzip.

  • gh-107409: Definido o atributo __wrapped__ em reprlib.recursive_repr().

  • gh-107406: Implementa o novo método __repr__() para struct.Struct. Agora ele retorna Struct(<format repr>).

  • gh-107369: Otimiza textwrap.indent(). Ele está ~30% mais rápido para entradas grandes. Patch por Inada Naoki.

  • gh-78722: Corrige o problema em que pathlib.Path.iterdir() não levantava OSError até ser iterado.

  • gh-105578: Descontinua typing.AnyStr em favor da nova sintaxe de parâmetro de tipo. Consulte PEP 695.

  • gh-62519: Faz com que gettext.pgettext() busque definições no plural quando a tradução não for encontrada.

  • gh-107089: Prateleiras abertas com shelve.open() têm um método clear() muito mais rápido. Patch por James Cave.

  • gh-82500: Corrige estouro em sistemas de 32 bits com a implementação de asyncio os.sendfile().

  • gh-83006: Documenta o comportamento de shutil.disk_usage() para sistemas de arquivos não montados no Unix.

  • gh-65495: Usa mail from e rcpt to em letras minúsculas em smptlib.SMTP.

  • gh-106186: Não reporta o defeito MultipartInvariantViolationDefect quando a classe email.parser.Parser for usada para analisar e-mails com headersonly=True.

  • gh-105002: Corrige resultado inválido do método PurePath.relative_to() ao tentar percorrer um segmento “..” em other com walk_up habilitado. Uma exceção ValueError agora é levantada neste caso.

  • gh-106739: Adiciona rtype_cache à mensagem de aviso (como um complemento ao tipo de objetos vazados e ao número de objetos vazados já incluídos na mensagem) para facilitar a depuração de objetos vazados quando o processo rastreador de recursos de multiprocessamento os encontra no desligamento. Isso ajuda a identificar mais rapidamente o que vazou e/ou por que o objeto vazado não foi limpo corretamente.

  • gh-106751: Otimiza SelectSelector.select() para muitos casos de iteração. Patch por Donghee Na.

  • gh-106751: Otimiza _PollLikeSelector.select() para o caso de muitas iterações.

  • gh-106751: Otimiza KqueueSelector.select() para o caso de muitas iterações. Patch por Donghee Na.

  • gh-106831: Corrige a possível ausência da verificação NULL do resultado d2i_SSL_SESSION em _ssl.c.

  • gh-105481: As diversas listas de opcodes no módulo dis agora são geradas a partir de bytecodes.c em vez de construídas explicitamente em opcode.py.

  • gh-106727: Torna inspect.getsource() mais inteligente para classes com definições de mesmo nome

  • gh-106789: Remove importação de pprint de sysconfig.

  • gh-105726: Adiciona __slots__ a contextlib.AbstractContextManager e contextlib.AbstractAsyncContextManager para que classes filhas possam usar __slots__.

  • gh-106774: Atualiza a cópia do pacote do pip para a versão 23.2.1.

  • gh-106751: selectors: Otimiza o código EpollSelector.select() movendo parte do código para fora do laço.

  • gh-106752: Corrigidos vários bugs em zipfile.Path, incluindo: em zipfile.Path.match(), os separadores do Windows não são mais respeitados (e nunca foram pensados para serem); Corrigidas as operações name/suffix/suffixes/stem quando nenhum nome de arquivo está presente e o Path não está na raiz do arquivo zip; Glob reformulado para melhor desempenho e comportamento de correspondência mais correto.

  • gh-105293: Removida a chamada para SSL_CTX_set_session_id_context durante a criação de contexto do lado do cliente no módulo ssl.

  • gh-106734: Desabilita o preenchimento automático com tabulação no modo multilinha de pdb

  • gh-105481: Exibido metadados do opcode por meio de _opcode.

  • gh-106670: Adiciona o novo comando exceptions ao depurador Pdb. Ele possibilita a navegação entre exceções encadeadas ao usar a depuração post mortem.

  • gh-106602: Adiciona __copy__ e __deepcopy__ em enum

  • gh-106664: selectors: Adiciona o método _SelectorMapping.get() e otimiza _SelectorMapping.__getitem__().

  • gh-106628: Acelera a análise de e-mails em cerca de 20%, eliminando a necessidade de compilar uma nova expressão regular para cada e-mail.

  • gh-89427: Define a variável de ambiente VIRTUAL_ENV_PROMPT na ativação de venv, mesmo quando VIRTUAL_ENV_DISABLE_PROMPT estiver definido.

  • gh-106530: Reverte uma alteração em colorsys.rgb_to_hls() que causava divisão por zero para certas entradas quase brancas. Patch por Terry Jan Reedy.

  • gh-106584: Corrige o código de saída para unittest caso todos os testes sejam ignorados. Patch por Egor Eliseev.

  • gh-106566: Otimiza (?!) (padrão que sempre falha) em expressões regulares.

  • gh-106554: selectors: Reduz a sobrecarga do seletor usando dict.get() para procurar descritores de arquivo.

  • gh-106558: Remove o ciclo de referência em chamadores de convert_to_error() excluindo result do escopo em um bloco finally.

  • gh-100502: Adiciona o atributo de classe pathlib.PurePath.pathmod que armazena a implementação de os.path usado para operações de caminho de baixo nível: posixpath ou ntpath.

  • gh-106527: Reduz a sobrecarga para adicionar e remover leitores e escritores asyncio.

  • gh-106524: Corrige a falha em _sre.template() com modelos contendo índices de grupo inválidos.

  • gh-106531: Removido _legacy e os nomes que ele fornecia de importlib.resources: Resource, contents, is_resource, open_binary, open_text, path, read_binary e read_text.

  • gh-106052: Módulo re: corrige a correspondência de quantificadores possessivos no caso de um subpadrão contendo retrocesso.

  • gh-106510: Melhora a saída de depuração para grupos atômicos em expressões regulares.

  • gh-106503: Corrige o ciclo de referência em asyncio._SelectorSocketTransport removendo _write_ready em close.

  • gh-105497: Corrige a inversão da máscara de sinalizador quando existem flags sem nome.

  • gh-90876: Impede que multiprocessing.spawn falhe na importação em ambientes onde sys.executable é None. Isso regrediu na versão 3.11 com a adição do suporte a objetos caminho ou similares em multiprocessamento.

  • gh-106403: Instâncias de typing.TypeVar, typing.ParamSpec, typing.ParamSpecArgs, typing.ParamSpecKwargs e typing.TypeVarTuple novamente oferecem suporte a referências fracas, corrigindo uma regressão introduzida no Python 3.12.0 beta 1. Patch por Jelle Zijlstra.

  • gh-89812: Adiciona a classe privada pathlib._PathBase, que fornece suporte experimental para sistemas de arquivos virtuais e pode ser disponibilizada publicamente em uma versão futura do Python.

  • gh-106292: Verifica se há um valor armazenado em cache do tipo dicionário instanciado no método __get__() de functools.cached_property(). Isso corresponde melhor ao comportamento anterior à versão 3.12 e melhora a compatibilidade para usuários que subclassificam functools.cached_property() e adicionam um método __set__().

  • gh-106350: Detecta possível falha de alocação de memória na função libtommath mp_init() usada pelo módulo _tkinter.

  • gh-106330: Corrige a correspondência incorreta de caminhos vazios em pathlib.PurePath.match(). Este bug foi introduzido no Python 3.12.0 beta 1.

  • gh-106309: Deprecate typing.no_type_check_decorator(). No major type checker ever added support for this decorator. Patch by Alex Waygood.

  • gh-102541: Faz com que pydoc.doc() capture o módulo inválido ImportError quando o fluxo de saída não for None.

  • gh-106263: Corrige a falha ao chamar repr com um objeto SignalDict construído manualmente. Patch por Charlie Zhao.

  • gh-106236: Substitui instruções assert por raise RuntimeError em threading, para que _DummyThread não possa ser unido nem mesmo com -OO.

  • gh-106238: Corrige bug raro de simultaneidade na aquisição de trava pelo pacote de registro.

  • gh-106152: Added PY_THROW event hook for cProfile for generators

  • gh-106075: Adicionado asyncio.taskgroups.__all__ a asyncio.__all__ para exportação em importações estrela.

  • gh-104527: O Zipapp agora ignora a anexação de um arquivo a si mesmo.

  • gh-106046: Melhoria na mensagem de erro de os.fspath() se chamada em um objeto onde __fspath__ está definido como None. Patch por Alex Waygood.

  • gh-105987: Corrige falha devido à contagem de referências incorreta nas rotinas internas ansiosas de fábrica de tarefas do do asyncio.

  • gh-105974: Corrige bug em que uma classe typing.Protocol que tinha um ou mais membros não-chamáveis levantava TypeError quando issubclass() era chamada contra ela, mesmo se definisse um método __subclasshook__ personalizado. O comportamento no Python 3.11 e versões anteriores — que agora foi restaurado — era não levantar TypeError nessas situações se um método __subclasshook__ personalizado fosse definido. Patch por Alex Waygood.

  • gh-96145: Revertida a adição de json.AttrDict.

  • gh-89812: Adiciona pathlib.UnsupportedOperation, que é levantada em vez de NotImplementedError quando uma operação de caminho não é suportada.

  • gh-105808: Corrigida uma regressão introduzida em gh-101251 para a versão 3.12, que fazia com que gzip.GzipFile.flush() não descarregasse o compactador (nem passasse o argumento zip_mode).

  • gh-105481: stack_effect() não levanta mais uma exceção se um oparg for fornecido para um opcode que não usa seu argumento, ou quando não for fornecido para um opcode que o utiliza. Neste último caso, o efeito de pilha é retornado para oparg=0.

  • gh-104799: Habilita ast.unparse() para desfazer o analisador sintático de definições de função e classe criadas sem o novo campo type_params de PEP 695. Patch por Jelle Zijlstra.

  • gh-105793: Adiciona o argumento somente-nomeado follow_symlinks para pathlib.Path.is_dir() e is_file(), com o padrão True.

  • gh-105570: Descontinua dois métodos de criação de classes typing.TypedDict com 0 campos usando a sintaxe funcional: TD = TypedDict("TD") e TD = TypedDict("TD", None). Ambos serão descontinuados no Python 3.15. Para criar uma classe TypedDict com 0 campos, use class TD(TypedDict): pass ou TD = TypedDict("TD", {}).

  • gh-105745: Corrige o método webbrowser.Konqueror.open.

  • gh-105733: ctypes: Descontinua as funções não documentadas ctypes.SetPointerType() e ctypes.ARRAY(). Patch por Victor Stinner.

  • gh-105687: Remove as funções descontinuadas re.template, re.T, re.TEMPLATE e sre_constans.SRE_FLAG_TEMPLATE.

  • gh-105684: O suporte a asyncio.Task.set_name() agora é obrigatório para implementações de tarefas de terceiros. A função não documentada _set_task_name() (descontinuada desde a versão 3.8) foi removida. Patch por Kumar Aditya.

  • gh-105375: Corrige um bug em _Unpickler_SetInputStream(), onde uma exceção poderia ser sobrescrita em caso de falha.

  • gh-105626: Altera o valor de retorno padrão de http.client.HTTPConnection.get_proxy_response_headers() para None e não {}.

  • gh-105375: Corrige bugs em sys, onde exceções poderiam ser sobrescritas devido ao tratamento de erros adiado.

  • gh-105605: Reforça o tratamento de erros em pyexpat durante a inicialização do módulo para evitar que exceções sejam sobrescritas e que objetos sejam desreferenciados duas vezes.

  • gh-105375: Corrige bug em decimal, onde uma exceção poderia acabar sendo sobrescrita.

  • gh-105375: Corrige bugs em _datetime, onde exceções poderiam ser sobrescritas em caso de falha na inicialização do módulo.

  • gh-105375: Corrige bugs na inicialização de _ssl, que poderiam levar a referências vazadas e exceções sobrescritas.

  • gh-105375: Corrige um bug em array.array, onde uma exceção poderia acabar sendo sobrescrita.

  • gh-105375: Corrige bugs em _ctypes, onde exceções poderiam ser sobrescritas.

  • gh-105375: Corrige um bug no módulo posix, onde uma exceção poderia ser sobrescrita.

  • gh-105375: Corrige bugs em _elementtree, onde exceções poderiam ser sobrescritas.

  • gh-105375: Corrige bugs em zoneinfo, onde exceções poderiam ser sobrescritas.

  • gh-105375: Corrige bugs em errno, onde exceções poderiam ser sobrescritas.

  • gh-105566: Descontinua a criação de uma classe typing.NamedTuple usando argumentos nomeados para denotar os campos (NT = NamedTuple("NT", x=int, y=str)). Isso não será permitido no Python 3.15. Use a sintaxe baseada em classe ou a sintaxe funcional.

    Dois métodos para criar classes NamedTuple com 0 campos usando a sintaxe funcional também estão descontinuados e não serão permitidos no Python 3.15: NT = NamedTuple("NT") e NT = NamedTuple("NT", None). Para criar uma classe NamedTuple com 0 campos, use class NT(NamedTuple): pass ou NT = NamedTuple("NT", []).

  • gh-105545: Remove o atributo webbrowser.MacOSXOSAScript._name, que estava descontinuado na versão 3.11.

  • gh-105497: Corrige a inversão de sinalizadores quando existem membros de apelido/máscara.

  • gh-105509: typing.Annotated agora é implementado como uma instância de typing._SpecialForm em vez de uma classe. Isso não deve ter impacto direto para os usuários da API pública do módulo typing.

  • gh-105375: Corrige bugs em pickle, onde exceções podiam ser sobrescritas.

  • gh-70303: Emite FutureWarning de pathlib.Path.glob() e rglob() se o padrão fornecido terminar com “**”. Em uma versão futura do Python, padrões com essa terminação corresponderão tanto a arquivos quanto a diretórios. Adicione uma barra final para corresponder apenas a diretórios.

  • gh-105375: Corrige um bug em sqlite3 onde uma exceção poderia ser sobrescrita no retorno de chamada de collation.

  • gh-105382: Remove os parâmetros cafile, capath e cadefault da função urllib.request.urlopen(), descontinuados no Python 3.6. Patch por Victor Stinner.

  • gh-105376: logging: Remove os métodos Logger.warn() e LoggerAdapter.warn() não documentados e não testados, bem como a função logging.warn(). Descontinuados desde o Python 3.3, eles eram apelidos dos métodos logging.Logger.warning(), logging.LoggerAdapter.warning() e logging.warning(). Patch por Victor Stinner.

  • gh-105332: Reverte o método de serialização com pickle de by-name para by-value.

  • gh-104554: Adiciona suporte ao esquema RTSPS em urllib.parse

  • gh-105292: Adiciona opção a traceback.format_exception_only() para recursivamente retornar à exceção aninhada de um BaseExceptionGroup.

  • gh-105280: Corrige bug em que isinstance([], collections.abc.Mapping) poderia ser avaliado como True se a coleta de lixo ocorresse no momento errado. O bug foi causado por alterações na implementação de typing.Protocol no Python 3.12.

  • gh-80480: array: Adiciona o typecode 'w' que representa Py_UCS4.

  • gh-105239: Corrige bug antigo em que issubclass(object, typing.Protocol) era avaliado como True em alguns casos extremos. Patch por Alex Waygood.

  • gh-104310: Na versão beta 1, adicionamos uma função utilitária para autores de módulos de extensão, para usar ao testar seus módulos quanto ao suporte em múltiplos interpretadores ou sob uma GIL por interpretador. O nome dessa função mudou de allowing_all_extensions para _incompatible_extension_module_restrictions. O padrão para o argumento “disable_check” foi alterado de “True” para “False”, para corresponder melhor ao novo nome da função.

  • gh-105080: Assinatura inconsistente corrigida em classes derivadas para inspect.signature()

  • gh-105144: Uma regressão recente foi corrigida no módulo typing. A regressão significava que executar class Foo(X, typing.Protocol), onde X era uma classe que tinha abc.ABCMeta como metaclasse, faria com que chamadas subsequentes de isinstance(1, X) levantassem erroneamente TypeError. Patch por Alex Waygood.

  • gh-62948: O finalizador io.IOBase agora registra os erros do método close() com sys.unraisablehook. Anteriormente, os erros eram ignorados silenciosamente por padrão e registrados apenas no Modo de Desenvolvimento Python ou no Python construído em modo de depuração. Patch por Victor Stinner.

  • gh-105096: wave: Descontinua os métodos getmark(), setmark() e getmarkers() das classes wave.Wave_read e wave.Wave_write. Eles serão removidos no Python 3.15. Patch por Victor Stinner.

  • gh-104992: Remove o método unittest.TestProgram.usageExit() não testado e não documentado, descontinuado no Python 3.11. Patch por Hugo van Kemenade.

  • gh-104996: Melhore o desempenho da inicialização de pathlib.PurePath adiando a junção de caminhos quando múltiplos argumentos são fornecidos.

  • gh-101588: Descontinua o suporte não documentado a copy/deepcopy/pickle para itertools.

  • gh-103631: Corrige pathlib.PurePosixPath(pathlib.PureWindowsPath(...)) que não convertia separadores de caminho para restaurar o comportamento compatível com a versão 3.11.

  • gh-104947: Torna as comparações entre objetos pathlib.PureWindowsPath consistentes no Windows e no Posix para corresponder ao comportamento da versão 3.11.

  • gh-104773: PEP 594: Remove o módulo audioop, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo aifc, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo uu, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104935: Corrige bugs na interação entre typing.runtime_checkable() e typing.Generic que foram introduzidos pela implementação PEP 695. Patch por Jelle Zijlstra.

  • gh-104773: PEP 594: Remove o módulo crypt e sua extensão privada _crypt, descontinuados no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo nis, obsoletos no Python 3.11. Patch por Victor Stinner.

  • gh-104898: Adiciona __slots__ ausente a os.PathLike.

  • gh-104773: PEP 594: Remove o módulo xdrlib, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo nntplib, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104886: Remove a classe não documentada configparser.LegacyInterpolation, descontinuada na documentação desde o Python 3.2 e com um aviso de descontinuação desde o Python 3.11. Patch por Hugo van Kemenade.

  • gh-104786: Remove a criação de typing.TypedDict baseada em kwargs.

  • gh-104876: Remove o método turtle.RawTurtle.settiltangle(), descontinuado na documentação desde o Python 3.1 e com um aviso de descontinuação desde o Python 3.11. Patch por Hugo van Kemenade.

  • gh-104773: PEP 594: Removido o pacote msilib, descontinuado no Python 3.11.

  • gh-104773: PEP 594: Removido o módulo spwd, descontinuado no Python 3.11: o projeto python-pam pode ser usado em seu lugar. Patch por Victor Stinner.

  • gh-75552: Removido o módulo tkinter.tix, descontinuado desde o Python 3.6.

  • gh-104773: PEP 594: Remove o módulo chunk, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo mailcap, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo sunau, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104780: PEP 594: Remove o módulo ossaudiodev, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104773: PEP 594: Remove o módulo pipes, descontinuado no Python 3.11. Patch por Victor Stinner.

  • gh-104873: Adiciona typing.get_protocol_members() para retornar o conjunto de membros que definem um typing.Protocol. Adiciona typing.is_protocol() para verificar se uma classe é um typing.Protocol. Patch por Jelle Zijlstra.

  • gh-104874: Documenta os atributos __name__ e __supertype__ de typing.NewType. Patch por Jelle Zijlstra.

  • gh-104835: Removidas as seguintes funções unittest, descontinuadas no Python 3.11:

    • unittest.findTestCases()

    • unittest.makeSuite()

    • unittest.getTestCaseNames()

    Em vez delas, use os métodos de TestLoader:

    Patch por Hugo van Kemenade.

  • gh-104804: Remove the untested and undocumented webbrowser MacOSX class, deprecated in Python 3.11. Patch by Hugo van Kemenade.

  • gh-83863: Support for using pathlib.Path objects as context managers has been removed. Before Python 3.9, exiting the context manager marked a path as “closed”, which caused some (but not all!) methods to raise when called. Since Python 3.9, using a path as a context manager does nothing.

  • gh-104799: Adjust the location of the (see PEP 695) type_params field on ast.ClassDef, ast.AsyncFunctionDef, and ast.FunctionDef to better preserve backward compatibility. Patch by Jelle Zijlstra

  • gh-104797: Allow typing.Protocol classes to inherit from collections.abc.Buffer. Patch by Jelle Zijlstra.

  • gh-104783: Remove locale.resetlocale() function deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104780: Remove the 2to3 program and the lib2to3 module, deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104773: PEP 594: Remove the telnetlib module, deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104773: PEP 594: Remove the imghdr module, deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104773: PEP 594: Remove the cgi and cgitb modules, deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104773: PEP 594: Remove the sndhdr module, deprecated in Python 3.11. Patch by Victor Stinner.

  • gh-104372: On Linux where subprocess can use the vfork() syscall for faster spawning, prevent the parent process from blocking other threads by dropping the GIL while it waits for the vfork’ed child process exec() outcome. This prevents spawning a binary from a slow filesystem from blocking the rest of the application.

  • gh-99108: We now release the GIL around built-in hashlib computations of reasonable size for the SHA families and MD5 hash functions, matching what our OpenSSL backed hash computations already does.

  • gh-102613: Improve performance of pathlib.Path.glob() when expanding a pattern with a non-terminal “**” component by filtering walked paths through a regular expression, rather than calling os.scandir() more than once on each directory.

  • gh-104399: Prepare the _tkinter module for building with Tcl 9.0 and future libtommath by replacing usage of deprecated functions mp_to_unsigned_bin_n() and mp_unsigned_bin_size() when necessary.

  • gh-102676: Add fields start_offset, cache_offset, end_offset, baseopname, baseopcode, jump_target and oparg to dis.Instruction.

  • gh-103558: Fixed parent argument validation mechanism of argparse. Improved test coverage.

  • gh-103464: Provide helpful usage messages when parsing incorrect pdb commands.

  • gh-103384: Generalize the regex pattern BaseConfigurator.INDEX_PATTERN to allow spaces and non-alphanumeric characters in keys.

  • gh-103124: Added multiline statement support for pdb

  • gh-101162: Forbid using builtins.issubclass() with types.GenericAlias as the first argument.

  • gh-103200: Fix cache repopulation semantics of zipimport.invalidate_caches(). The cache is now repopulated upon retrieving files with an invalid cache, not when the cache is invalidated.

  • gh-100061: Fix a bug that causes wrong matches for regular expressions with possessive qualifier.

  • gh-77609: Add follow_symlinks argument to pathlib.Path.glob() and rglob(), defaulting to false.

  • gh-102541: Hide traceback in help() prompt, when import failed.

  • gh-102120: Added a stream mode to tarfile that allows for reading archives without caching info about the inner files.

  • gh-102029: Deprecate passing any arguments to threading.RLock().

  • gh-88233: Refactored zipfile._strip_extra to use higher level abstractions for extras instead of a heavy-state loop.

  • gh-102024: Reduce calls of _idle_semaphore.release() in concurrent.futures.thread._worker().

  • gh-73435: Add support for recursive wildcards in pathlib.PurePath.match().

  • gh-84867: unittest.TestLoader no longer loads test cases from exact unittest.TestCase and unittest.FunctionTestCase classes.

  • gh-99203: Restore following CPython <= 3.10.5 behavior of shutil.make_archive(): do not create an empty archive if root_dir is not a directory, and, in that case, raise FileNotFoundError or NotADirectoryError regardless of format choice. Beyond the brought-back behavior, the function may now also raise these exceptions in dry_run mode.

  • gh-80480: Emit DeprecationWarning for array’s 'u' type code, deprecated in docs since Python 3.3.

  • gh-94924: unittest.mock.create_autospec() now properly returns coroutine functions compatible with inspect.iscoroutinefunction()

  • gh-94777: Fix hanging multiprocessing ProcessPoolExecutor when a child process crashes while data is being written in the call queue.

  • gh-92871: Remove the typing.io and typing.re namespaces, deprecated since Python 3.8. All items are still available from the main typing module.

  • bpo-43633: Improve the textual representation of IPv4-mapped IPv6 addresses (RFC 4291 Sections 2.2, 2.5.5.2) in ipaddress. Patch by Oleksandr Pavliuk.

  • bpo-44850: Improve performance of operator.methodcaller() using the PEP 590 vectorcall convention. Patch by Anthony Lee and Pieter Eendebak.

  • bpo-44185: unittest.mock.mock_open() will call the close() method of the file handle mock when it is exiting from the context manager. Patch by Samet Yaslan.

  • bpo-40988: Improve performance of functools.singledispatchmethod by caching the generated dispatch wrapper. Optimization suggested by frederico. Patch by @mental32, Alex Waygood and Pieter Eendebak.

  • bpo-41768: unittest.mock speccing no longer calls class properties. Patch by Melanie Witt.

  • bpo-18319: Ensure gettext(msg) retrieve translations even if a plural form exists. In other words: gettext(msg) == ngettext(msg, '', 1).

  • bpo-17013: Add ThreadingMock to unittest.mock that can be used to create Mock objects that can wait until they are called. Patch by Karthikeyan Singaravelan and Mario Corchero.

Documentação

Testes

  • gh-110647: Fix test_stress_modifying_handlers() of test_signal. Patch by Victor Stinner.

  • gh-103053: Fix test_tools.test_freeze on FreeBSD: run “make distclean” instead of “make clean” in the copied source directory to remove also the “python” program. Patch by Victor Stinner.

  • gh-110167: Fix a deadlock in test_socket when server fails with a timeout but the client is still running in its thread. Don’t hold a lock to call cleanup functions in doCleanups(). One of the cleanup function waits until the client completes, whereas the client could deadlock if it called addCleanup() in such situation. Patch by Victor Stinner.

  • gh-110388: Add tests for tty.

  • gh-81002: Add tests for termios.

  • gh-110367: regrtest: When using worker processes (-jN) with –verbose3 option, regrtest can now display the worker output even if a worker process does crash. Previously, sys.stdout and sys.stderr were replaced and so the worker output was lost on a crash. Patch by Victor Stinner.

  • gh-110267: Add tests for pickling and copying PyStructSequence objects. Patched by Xuehai Pan.

  • gh-110171: libregrtest now always sets and shows random.seed, so tests are more reproducible. Use --randseed flag to pass the explicit random seed for tests.

  • gh-110152: Remove Tools/scripts/run_tests.py and make hostrunnertest. Just run ./python -m test --slow-ci, make buildbottest or make test instead. Python test runner (regrtest) now handles cross-compilation and HOSTRUNNER. It also adds options to Python such fast -u -E -W default -bb when --fast-ci or --slow-ci option is used. Patch by Victor Stinner.

  • gh-110031: Skip test_threading tests using thread+fork if Python is built with Address Sanitizer (ASAN). Patch by Victor Stinner.

  • gh-110088: Fix test_asyncio timeouts: don’t measure the maximum duration, a test should not measure a CI performance. Only measure the minimum duration when a task has a timeout or delay. Add CLOCK_RES to test_asyncio.utils. Patch by Victor Stinner.

  • gh-109974: Fix race conditions in test_threading lock tests. Wait until a condition is met rather than using time.sleep() with a hardcoded number of seconds. Patch by Victor Stinner.

  • gh-110033: Fix test_interprocess_signal() of test_signal. Make sure that the subprocess.Popen object is deleted before the test raising an exception in a signal handler. Otherwise, Popen.__del__() can get the exception which is logged as Exception ignored in: ... and the test fails. Patch by Victor Stinner.

  • gh-109594: Fix test_timeout() of test_concurrent_futures.test_wait. Remove the future which may or may not complete depending if it takes longer than the timeout or not. Keep the second future which does not complete before wait() timeout. Patch by Victor Stinner.

  • gh-109972: Split test_gdb.py file into a test_gdb package made of multiple tests, so tests can now be run in parallel. Patch by Victor Stinner.

  • gh-109566: regrtest: When --fast-ci or --slow-ci option is used, regrtest now replaces the current process with a new process to add -u -W default -bb -E options to Python. Patch by Victor Stinner.

  • gh-109748: Fix test_zippath_from_non_installed_posix() of test_venv: don’t copy __pycache__/ sub-directories, because they can be modified by other Python tests running in parallel. Patch by Victor Stinner.

  • gh-109739: regrtest: Fix reference leak check on Windows. Disable the load tracker on Windows in the reference leak check mode (-R option). Patch by Victor Stinner.

  • gh-109276: regrtest: When a test fails with “env changed” and the –rerun option is used, the test is now re-run in verbose mode in a fresh process. Patch by Victor Stinner.

  • gh-103053: Skip test_freeze_simple_script() of test_tools.test_freeze if Python is built with ./configure --enable-optimizations, which means with Profile Guided Optimization (PGO): it just makes the test too slow. The freeze tool is tested by many other CIs with other (faster) compiler flags. Patch by Victor Stinner.

  • gh-109580: Skip test_perf_profiler if Python is built with ASAN, MSAN or UBSAN sanitizer. Python does crash randomly in this test on such build. Patch by Victor Stinner.

  • gh-109566: regrtest: Add --fast-ci and --slow-ci options. --fast-ci uses a default timeout of 10 minutes and -u all,-cpu (skip slowest tests). --slow-ci uses a default timeout of 20 minutes and -u all (run all tests). Patch by Victor Stinner.

  • gh-109425: libregrtest now decodes stdout of test worker processes with the “backslashreplace” error handler to log corrupted stdout, instead of failing with an error and not logging the stdout. Patch by Victor Stinner.

  • gh-109396: Fix test_socket.test_hmac_sha1() in FIPS mode. Use a longer key: FIPS mode requires at least of at least 112 bits. The previous key was only 32 bits. Patch by Victor Stinner.

  • gh-104736: Fix test_gdb on Python built with LLVM clang 16 on Linux ppc64le (ex: Fedora 38). Search patterns in gdb “bt” command output to detect when gdb fails to retrieve the traceback. For example, skip a test if Backtrace stopped: frame did not save the PC is found. Patch by Victor Stinner.

  • gh-109276: libregrtest now calls random.seed() before running each test file when -r/--randomize command line option is used. Moreover, it’s also called in worker processes. It should help to make tests more deterministic. Previously, it was only called once in the main process before running all test files and it was not called in worker processes. Patch by Victor Stinner.

  • gh-109276: libregrtest now uses a separated file descriptor to write test result as JSON. Previously, if a test wrote debug messages late around the JSON, the main test process failed to parse JSON. Patch by Victor Stinner.

  • gh-108996: Fix and enable test_msvcrt.

  • gh-109237: Fix test_site.test_underpth_basic() when the working directory contains at least one non-ASCII character: encode the ._pth file to UTF-8 and enable the UTF-8 Mode to use UTF-8 for the child process stdout. Patch by Victor Stinner.

  • gh-109230: Fix test_pyexpat.test_exception(): it can now be run from a directory different than Python source code directory. Before, the test failed in this case. Skip the test if Modules/pyexpat.c source is not available. Skip also the test on Python implementations other than CPython. Patch by Victor Stinner.

  • gh-108996: Add tests for msvcrt.

  • gh-109015: Fix test_asyncio, test_imaplib and test_socket tests on FreeBSD if the TCP blackhole is enabled (sysctl net.inet.tcp.blackhole). Skip the few tests which failed with ETIMEDOUT which such non standard configuration. Currently, the FreeBSD GCP image enables TCP and UDP blackhole (sysctl net.inet.tcp.blackhole=2 and sysctl net.inet.udp.blackhole=1). Patch by Victor Stinner.

  • gh-91960: Skip test_gdb if gdb is unable to retrieve Python frame objects: if a frame is <optimized out>. When Python is built with “clang -Og”, gdb can fail to retrieve the frame parameter of _PyEval_EvalFrameDefault(). In this case, tests like py_bt() are likely to fail. Without getting access to Python frames, python-gdb.py is mostly clueless on retrieving the Python traceback. Moreover, test_gdb is no longer skipped on macOS if Python is built with Clang. Patch by Victor Stinner.

  • gh-108962: Skip test_tempfile.test_flags() if chflags() fails with “OSError: [Errno 45] Operation not supported” (ex: on FreeBSD 13). Patch by Victor Stinner.

  • gh-91960: FreeBSD 13.2 CI coverage for pull requests is now provided by Cirrus-CI (a hosted CI service that supports Linux, macOS, Windows, and FreeBSD).

  • gh-89392: Removed support of test_main() function in tests. They now always use normal unittest test runner.

  • gh-108851: Fix test_tomllib recursion tests for WASI buildbots: reduce the recursion limit and compute the maximum nested array/dict depending on the current available recursion limit. Patch by Victor Stinner.

  • gh-108851: Add get_recursion_available() and get_recursion_depth() functions to the test.support module. Patch by Victor Stinner.

  • gh-108834: Add --fail-rerun option option to regrtest: if a test failed when then passed when rerun in verbose mode, exit the process with exit code 2 (error), instead of exit code 0 (success). Patch by Victor Stinner.

  • gh-108834: Rename regrtest --verbose2 option (-w) to --rerun. Keep --verbose2 as a deprecated alias. Patch by Victor Stinner.

  • gh-108834: When regrtest reruns failed tests in verbose mode (./python -m test --rerun), tests are now rerun in fresh worker processes rather than being executed in the main process. If a test does crash or is killed by a timeout, the main process can detect and handle the killed worker process. Tests are rerun in parallel if the -jN option is used to run tests in parallel. Patch by Victor Stinner.

  • gh-108822: regrtest now computes statistics on all tests: successes, failures and skipped. test_netrc, test_pep646_syntax and test_xml_etree now return results in their test_main() function. Patch by Victor Stinner and Alex Waygood.

  • gh-108794: The doctest.DocTestRunner.run() method now counts the number of skipped tests. Add doctest.DocTestRunner.skips and doctest.TestResults.skipped attributes. Patch by Victor Stinner.

  • gh-108388: Convert test_concurrent_futures to a package of 7 sub-tests. Patch by Victor Stinner.

  • gh-108388: Split test_multiprocessing_fork, test_multiprocessing_forkserver and test_multiprocessing_spawn into test packages. Each package is made of 4 sub-tests: processes, threads, manager and misc. It allows running more tests in parallel and so reduce the total test duration. Patch by Victor Stinner.

  • gh-105776: Fix test_cppext when the C compiler command -std=c11 option: remove -std= options from the compiler command. Patch by Victor Stinner.

  • gh-107652: Set up CIFuzz to run fuzz targets in GitHub Actions. Patch by Illia Volochii.

  • gh-107237: test_logging: Fix test_udp_reconnection() by increasing the timeout from 100 ms to 5 minutes (LONG_TIMEOUT). Patch by Victor Stinner.

  • gh-107178: Add the C API test for functions in the Mapping Protocol, the Sequence Protocol and some functions in the Object Protocol.

  • gh-106714: test_capi: Fix test_no_FatalError_infinite_loop() to no longer write a coredump, by using test.support.SuppressCrashReport. Patch by Victor Stinner.

  • gh-104090: Avoid creating a reference to the test object in collectedDurations().

  • gh-106752: Moved tests for zipfile.Path into Lib/test/test_zipfile/_path. Made zipfile._path a package.

  • gh-106690: Add .coveragerc to cpython repository for use with coverage package.

  • gh-101634: When running the Python test suite with -jN option, if a worker stdout cannot be decoded from the locale encoding report a failed testn so the exitcode is non-zero. Patch by Victor Stinner.

  • gh-105084: When the Python build is configured --with-wheel-pkg-dir, tests requiring the setuptools and wheel wheels will search for the wheels in WHEEL_PKG_DIR.

  • gh-81005: String tests are modified to reflect that str and unicode are merged in Python 3. Patch by Daniel Fortunov.

  • gh-103186: Suppress and assert expected RuntimeWarnings in test_sys_settrace.py

  • gh-69714: Add additional tests to calendar to achieve full test coverage.

Construção

  • gh-103053: “make check-clean-src” now also checks if the “python” program is found in the source directory: fail with an error if it does exist. Patch by Victor Stinner.

  • gh-109191: Fix compile error when building with recent versions of libedit.

  • gh-110276: No longer ignore PROFILE_TASK failure silently: command used by Profile Guided Optimization (PGO). Patch by Victor Stinner.

  • gh-109566: Remove make testall target: use make buildbottest instead. Patch by Victor Stinner.

  • gh-109740: The experimental --disable-gil configure flag now includes “t” (for “threaded”) in extension ABI tags.

  • gh-109054: Fix building the _testcapi extension on Linux AArch64 which requires linking to libatomic when <cpython/pyatomic.h> is used: the _Py_atomic_or_uint64() function requires libatomic __atomic_fetch_or_8() on this platform. The configure script now checks if linking to libatomic is needed and generates a new LIBATOMIC variable used to build the _testcapi extension. Patch by Victor Stinner.

  • gh-63760: Fix Solaris build: no longer redefine the gethostname() function. Solaris defines the function since 2005. Patch by Victor Stinner, original patch by Jakub Kulík.

  • gh-108740: Fix a race condition in make regen-all. The deepfreeze.c source and files generated by Argument Clinic are now generated or updated before generating “global objects”. Previously, some identifiers may miss depending on the order in which these files were generated. Patch by Victor Stinner.

  • gh-108634: Python built with configure --with-trace-refs (tracing references) is now ABI compatible with Python release build and debug build. Patch by Victor Stinner.

  • gh-85283: The _stat C extension is now built with the limited C API. Patch by Victor Stinner.

  • gh-108447: Fix x86_64 GNU/Hurd build

  • gh-107814: When calling find_python.bat with -q it did not properly silence the output of nuget. That is now fixed.

  • gh-105481: Remove the make target regen-opcode-targets, merge its work into regen-opcode which repeats most of the calculation. This simplifies the code for the build and reduces code duplication.

  • gh-106881: Check for linux/limits.h before including it in Modules/posixmodule.c.

  • gh-95855: Refactor platform triplet detection code and add detection for MIPS soft float and musl libc.

  • gh-106962: Detect MPI compilers in configure.

  • gh-106118: Fix compilation for platforms without O_CLOEXEC. The issue was introduced with Python 3.12b1 in gh-103295. Patch by Erlend Aasland.

  • gh-105875: SQLite 3.15.2 or newer is required to build the sqlite3 extension module. Patch by Erlend Aasland.

  • gh-90005: Fix a regression in configure where we could end up unintentionally linking with libbsd.

  • gh-102404: Document how to perform a WASI build on Linux. Also add Tools/wasm/build_wasi.sh as a reference implementation of the docs.

  • gh-89886: Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate configure.

  • gh-104692: Include commoninstall as a prerequisite for bininstall

    This ensures that commoninstall is completed before bininstall is started when parallel builds are used (make -j install), and so the python3 symlink is only installed after all standard library modules are installed.

  • gh-101538: Add experimental wasi-threads support. Patch by Takashi Yamamoto.

Windows

  • gh-110437: Allows overriding the source of VC redistributables so that releases can be guaranteed to never downgrade between updates.

  • gh-109286: Update Windows installer to use SQLite 3.43.1.

  • gh-82367: os.path.realpath() now resolves MS-DOS style file names even if the file is not accessible. Patch by Moonsik Park.

  • gh-109991: Update Windows build to use OpenSSL 3.0.11.

  • gh-106242: Fixes realpath() to behave consistently when passed a path containing an embedded null character on Windows. In strict mode, it now raises OSError instead of the unexpected ValueError, and in non-strict mode will make the path absolute.

  • gh-83180: Changes the Gerenciador de instalação do Python to prefer an active virtual environment when the launched script has a shebang line using a Unix-like virtual command, even if the command requests a specific version of Python.

  • gh-106844: Fix integer overflow and truncating by the null character in _winapi.LCMapStringEx() which affects ntpath.normcase().

  • gh-105436: Ensure that an empty environment block is terminated by two null characters, as is required by Windows.

  • gh-105146: Updated the links at the end of the installer to point to Discourse rather than the mailing lists.

  • gh-103646: When installed from the Microsoft Store, pip no longer defaults to per-user installs. However, as the install directory is unwritable, it should automatically decide to do a per-user install anyway. This should resolve issues when pip is passed an option that conflicts with --user.

  • gh-88745: Improve performance of shutil.copy2() by using the operating system’s CopyFile2 function. This may result in subtle changes to metadata copied along with some files, bringing them in line with normal OS behavior.

  • gh-104820: Fixes stat() and related functions on file systems that do not support file ID requests. This includes FAT32 and exFAT.

  • gh-104803: Add os.path.isdevdrive() to detect whether a path is on a Windows Dev Drive. Returns False on platforms that do not support Dev Drive, and is absent on non-Windows platforms.

macOS

  • gh-109286: Update macOS installer to use SQLite 3.43.1.

  • gh-109991: Atualiza o instalador do macOS para usar OpenSSL 3.0.11.

  • gh-99079: Atualiza o instalador do macOS para usar OpenSSL 3.0.9.

IDLE

  • gh-104719: Remove IDLE’s modification of tokenize.tabsize and test other uses of tokenize data and methods.

Ferramentas/Demos

  • gh-109991: Update GitHub CI workflows to use OpenSSL 3.0.11 and multissltests to use 1.1.1w, 3.0.11, and 3.1.3.

  • gh-108494: Argument Clinic now has a partial support of the Limited API: see documentation in the Python Developer’s Guide Patch by Victor Stinner.

  • gh-107704: It is now possible to deprecate passing keyword arguments for keyword-or-positional parameters with Argument Clinic, using the new / [from X.Y] syntax. (To be read as “positional-only from Python version X.Y”.) See documentation in the Python Developer’s Guide for more information.

  • gh-107880: Argument Clinic can now clone __init__() and __new__() methods.

  • gh-104683: Add --exclude option to Argument Clinic CLI.

  • gh-95065: Argument Clinic now supports overriding automatically generated signature by using directive @text_signature. See documentation in the Python Developer’s Guide

  • gh-107609: Fix duplicate module check in Argument Clinic. Previously, a duplicate definition would incorrectly be silently accepted. Patch by Erlend E. Aasland.

  • gh-107467: The Argument Clinic command-line tool now prints to stderr instead of stdout on failure.

  • gh-106970: Fix bugs in the Argument Clinic destination <name> clear command; the destination buffers would never be cleared, and the destination directive parser would simply continue to the fault handler after processing the command. Patch by Erlend E. Aasland.

  • gh-106706: Change bytecode syntax for families to remove redundant name matching pseudo syntax.

  • gh-106359: Argument Clinic now explicitly forbids “kwarg splats” in function calls used as annotations.

  • gh-103186: freeze now fetches CONFIG_ARGS from the original CPython instance the Makefile uses to call utility scripts. Patch by Ijtaba Hussain.

  • gh-95065: It is now possible to deprecate passing parameters positionally with Argument Clinic, using the new * [from X.Y] syntax. (To be read as “keyword-only from Python version X.Y”.) See documentation in the Python Developer’s Guide for more information. Patch by Erlend E. Aasland with help from Alex Waygood, Nikita Sobolev, and Serhiy Storchaka.

API C

  • gh-85283: If the Py_LIMITED_API macro is defined, Py_BUILD_CORE, Py_BUILD_CORE_BUILTIN and Py_BUILD_CORE_MODULE macros are now undefined by <Python.h>. Patch by Victor Stinner.

  • gh-110289: Add PyUnicode_EqualToUTF8AndSize() and PyUnicode_EqualToUTF8() functions.

  • gh-110235: Raise TypeError for duplicate/unknown fields in PyStructSequence constructor. Patched by Xuehai Pan.

  • gh-110014: Remove undocumented PY_TIMEOUT_MAX constant from the limited C API. Patch by Victor Stinner.

  • gh-109521: PyImport_GetImporter() now sets RuntimeError if it fails to get sys.path_hooks or sys.path_importer_cache or they are not list and dict correspondingly. Previously it could return NULL without setting error in obscure cases, crash or raise SystemError if these attributes have wrong type.

  • gh-108724: Add PyMutex internal-only lightweight locking API.

  • gh-85283: Add PySys_AuditTuple() function: similar to PySys_Audit(), but pass event arguments as a Python tuple object. Patch by Victor Stinner.

  • gh-108867: Add PyThreadState_GetUnchecked() function: similar to PyThreadState_Get(), but don’t kill the process with a fatal error if it is NULL. The caller is responsible to check if the result is NULL. Previously, the function was private and known as _PyThreadState_UncheckedGet(). Patch by Victor Stinner.

  • gh-108765: Python.h no longer includes the <ctype.h> standard header file. If needed, it should now be included explicitly. For example, it provides isalpha() and tolower() functions which are locale dependent. Python provides locale independent functions, like Py_ISALPHA() and Py_TOLOWER(). Patch by Victor Stinner.

  • gh-108765: Python.h no longer includes the <unistd.h> standard header file. If needed, it should now be included explicitly. For example, it provides the functions: close(), getpagesize(), getpid() and sysconf(). Patch by Victor Stinner.

  • gh-108765: Python.h no longer includes the <ieeefp.h> standard header. It was included for the finite() function which is now provided by the <math.h> header. It should now be included explicitly if needed. Remove also the HAVE_IEEEFP_H macro. Patch by Victor Stinner.

  • gh-108765: Python.h no longer includes these standard header files: <time.h>, <sys/select.h> and <sys/time.h>. If needed, they should now be included explicitly. For example, <time.h> provides the clock() and gmtime() functions, <sys/select.h> provides the select() function, and <sys/time.h> provides the futimes(), gettimeofday() and setitimer() functions. Patch by Victor Stinner.

  • gh-108511: Add functions PyObject_HasAttrWithError(), PyObject_HasAttrStringWithError(), PyMapping_HasKeyWithError() and PyMapping_HasKeyStringWithError().

  • gh-107073: Add PyObject_VisitManagedDict() and PyObject_ClearManagedDict() functions which must be called by the traverse and clear functions of a type using Py_TPFLAGS_MANAGED_DICT flag. Patch by Victor Stinner.

  • gh-108634: Python built with configure --with-trace-refs (tracing references) now supports the Limited API. Patch by Victor Stinner.

  • gh-108014: Add PyLong_AsInt() function: similar to PyLong_AsLong(), but store the result in a C int instead of a C long. Previously, it was known as the private function _PyLong_AsInt() (with an underscore prefix). Patch by Victor Stinner.

  • gh-108314: Add PyDict_ContainsString() function: same as PyDict_Contains(), but key is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*. Patch by Victor Stinner.

  • gh-108337: Adiciona operações atômicas em tipos de dados adicionais em pyatomic.h.

  • gh-108014: Add Py_IsFinalizing() function: check if the main Python interpreter is shutting down. Patch by Victor Stinner.

  • gh-107916: C API functions PyErr_SetFromErrnoWithFilename(), PyErr_SetExcFromWindowsErrWithFilename() and PyErr_SetFromWindowsErrWithFilename() save now the error code before calling PyUnicode_DecodeFSDefault().

  • gh-107915: Such C API functions as PyErr_SetString(), PyErr_Format(), PyErr_SetFromErrnoWithFilename() and many others no longer crash or ignore errors if it failed to format the error message or decode the filename. Instead, they keep a corresponding error.

  • gh-107810: Improve DeprecationWarning for uses of PyType_Spec with metaclasses that have custom tp_new.

  • gh-107249: Implement the Py_UNUSED macro for Windows MSVC compiler. Patch by Victor Stinner.

  • gh-107226: PyModule_AddObjectRef() is now only available in the limited API version 3.10 or later.

  • gh-106320: Remove private _PyUnicode_AsString() alias to PyUnicode_AsUTF8(). It was kept for backward compatibility with Python 3.0 - 3.2. The PyUnicode_AsUTF8() is available since Python 3.3. The PyUnicode_AsUTF8String() function can be used to keep compatibility with Python 3.2 and older. Patch by Victor Stinner.

  • gh-106572: Convert PyObject_DelAttr() and PyObject_DelAttrString() macros to functions. Patch by Victor Stinner.

  • gh-106307: Add PyMapping_GetOptionalItem() function.

  • gh-106521: Add PyObject_GetOptionalAttr() and PyObject_GetOptionalAttrString() functions.

  • gh-106320: Remove _PyInterpreterState_Get() alias to PyInterpreterState_Get() which was kept for backward compatibility with Python 3.8. Patch by Victor Stinner.

  • gh-106316: Remove cpython/pytime.h header file: it only contained private functions. Patch by Victor Stinner.

  • gh-106023: Remove private _PyObject_FastCall() function: use PyObject_Vectorcall() which is available since Python 3.8 (PEP 590). Patch by Victor Stinner.

  • gh-106168: If Python is built in debug mode or with assertions, PyTuple_SET_ITEM() and PyList_SET_ITEM() now check the index argument with an assertion. If the assertion fails, make sure that the size is set before. Patch by Victor Stinner.

  • gh-106084: Remove the old aliases to functions calling functions which were kept for backward compatibility with Python 3.8 provisional API:

    • _PyObject_CallMethodNoArgs(): use PyObject_CallMethodNoArgs()

    • _PyObject_CallMethodOneArg(): use PyObject_CallMethodOneArg()

    • _PyObject_CallOneArg(): use PyObject_CallOneArg()

    • _PyObject_FastCallDict(): use PyObject_VectorcallDict()

    • _PyObject_Vectorcall(): use PyObject_Vectorcall()

    • _PyObject_VectorcallMethod(): use PyObject_VectorcallMethod()

    • _PyVectorcall_Function(): use PyVectorcall_Function()

    Just remove the underscore prefix to update your code. Patch by Victor Stinner.

  • gh-106004: Adds PyDict_GetItemRef() and PyDict_GetItemStringRef() functions: similar to PyDict_GetItemWithError() but returning a strong reference instead of a borrowed reference. Patch by Victor Stinner.

  • gh-105927: Deprecate the PyWeakref_GetObject() and PyWeakref_GET_OBJECT() functions: use the new PyWeakref_GetRef() function instead. Patch by Victor Stinner.

  • gh-105927: Add PyWeakref_GetRef() function: similar to PyWeakref_GetObject() but returns a strong reference, or NULL if the referent is no longer live. Patch by Victor Stinner.

  • gh-105922: Add PyImport_AddModuleRef(): similar to PyImport_AddModule(), but return a strong reference instead of a borrowed reference. Patch by Victor Stinner.

  • gh-105227: The new PyType_GetDict() provides the dictionary for the given type object that is normally exposed by cls.__dict__. Normally it’s sufficient to use tp_dict, but for the static builtin types tp_dict is now always NULL. PyType_GetDict() provides the correct dict object instead.

  • gh-105375: Fix a bug in PyErr_WarnExplicit() where an exception could end up being overwritten if the API failed internally.

  • gh-105603: We’ve renamed the new (in 3.12) PyInterpreterConfig.own_gil to PyInterpreterConfig.gil and changed the meaning of the value from “bool” to an integer with supported values of PyInterpreterConfig_DEFAULT_GIL, PyInterpreterConfig_SHARED_GIL, and PyInterpreterConfig_OWN_GIL. The default is “shared”.

  • gh-105387: In the limited C API version 3.12, Py_INCREF() and Py_DECREF() functions are now implemented as opaque function calls to hide implementation details. Patch by Victor Stinner.

  • gh-105396: Deprecate the PyImport_ImportModuleNoBlock() function which is just an alias to PyImport_ImportModule() since Python 3.3. Patch by Victor Stinner.

  • gh-103968: PyType_FromMetaclass() now allows metaclasses with tp_new set to NULL.

  • gh-105268: Remove the old private, undocumented and untested _PyGC_FINALIZED() macro which was kept for backward compatibility with Python 3.8 and older. Patch by Victor Stinner.

  • gh-105182: Remove PyEval_AcquireLock() and PyEval_ReleaseLock() functions, deprecated in Python 3.2. Patch by Victor Stinner.

  • gh-105182: Remove PyEval_InitThreads() and PyEval_ThreadsInitialized() functions, deprecated in Python 3.9. Patch by Victor Stinner.

  • gh-105145: Deprecate old Python initialization functions:

    • PySys_ResetWarnOptions()

    • Py_GetExecPrefix()

    • Py_GetPath()

    • Py_GetPrefix()

    • Py_GetProgramFullPath()

    • Py_GetProgramName()

    • Py_GetPythonHome()

    Patch por Victor Stinner.

  • gh-85275: PyObject_AsCharBuffer(), PyObject_AsReadBuffer(), PyObject_CheckReadBuffer(), and PyObject_AsWriteBuffer() are removed. Please migrate to new buffer protocol; PyObject_GetBuffer() and PyBuffer_Release().

  • gh-105156: Deprecate the old Py_UNICODE and PY_UNICODE_TYPE types: use directly the wchar_t type instead. Since Python 3.3, Py_UNICODE and PY_UNICODE_TYPE are just aliases to wchar_t. Patch by Victor Stinner.

  • gh-105145: Remove the following old functions to configure the Python initialization, deprecated in Python 3.11:

    • PySys_AddWarnOptionUnicode()

    • PySys_AddWarnOption()

    • PySys_AddXOption()

    • PySys_HasWarnOptions()

    • PySys_SetArgvEx()

    • PySys_SetArgv()

    • PySys_SetPath()

    • Py_SetPath()

    • Py_SetProgramName()

    • Py_SetPythonHome()

    • Py_SetStandardStreamEncoding()

    • _Py_SetProgramFullPath()

    Patch por Victor Stinner.

  • gh-105107: Remove functions deprecated in Python 3.9.

    Patch por Victor Stinner.

  • gh-105115: PyTypeObject.tp_bases (and tp_mro) for builtin static types are now shared by all interpreters, whereas in 3.12-beta1 they were stored on PyInterpreterState. Also note that now the tuples are immortal objects.

  • gh-105071: Add PyUnstable_Exc_PrepReraiseStar to the unstable C api to expose the implementation of except*.

  • gh-104922: PY_SSIZE_T_CLEAN is no longer required to use '#' formats in APIs like PyArg_ParseTuple() and Py_BuildValue(). They uses Py_ssize_t for '#' regardless PY_SSIZE_T_CLEAN.

  • gh-104584: Add an unstable C API for hooking in an optimizer. This is mainly internal, but marked “unstable” to allow third-party experimentation.

  • gh-104668: Don’t call PyOS_InputHook or PyOS_ReadlineFunctionPointer in subinterpreters, since it’s generally difficult to avoid using global state in their registered callbacks. This also avoids situations where extensions may find themselves running in a subinterpreter they don’t support (or haven’t yet been loaded in).

  • bpo-42327: Add PyModule_Add() function: similar to PyModule_AddObjectRef() and PyModule_AddObject(), but always steals a reference to the value.

  • bpo-40309: Properly handle trailing spaces before closing parenthesis in Py_BuildValue() format strings.

Python 3.12.0 beta 1

Data de lançamento: 2023-05-22

Segurança

  • gh-99889: Fixed a security in flaw in uu.decode() that could allow for directory traversal based on the input if no out_file was specified.

  • gh-104049: Do not expose the local on-disk location in directory indexes produced by http.client.SimpleHTTPRequestHandler.

  • gh-99108: Upgrade built-in hashlib SHA3 implementation to a verified implementation from the HACL* project. Used when OpenSSL is not present or lacks SHA3.

  • gh-102153: urllib.parse.urlsplit() now strips leading C0 control and space characters following the specification for URLs defined by WHATWG in response to CVE 2023-24329. Patch by Illia Volochii.

Biblioteca

  • gh-102856: Implement PEP 701 changes in the tokenize module. Patch by Marta Gómez Macías and Pablo Galindo Salgado

Núcleo e embutidos

  • gh-104615: Fix wrong ordering of assignments in code like a, a = x, y. Contributed by Carl Meyer.

  • gh-104572: Improve syntax error message for invalid constructs in PEP 695 contexts and in annotations when from __future__ import annotations is active.

  • gh-104482: Fix three error handling bugs in ast.c’s validation of pattern matching statements.

  • gh-102818: Do not add a frame to the traceback in the sys.setprofile and sys.settrace trampoline functions. This ensures that frames are not duplicated if an exception is raised in the callback function, and ensures that frames are not omitted if a C callback is used and that does not add the frame.

  • gh-104405: Fix an issue where some bytecode instructions could ignore PEP 523 when “inlining” calls.

  • gh-103082: Change behavior of sys.monitoring.events.LINE events in sys.monitoring: Line events now occur when a new line is reached dynamically, instead of using a static approximation, as before. This makes the behavior very similar to that of “line” events in sys.settrace. This should ease porting of tools from 3.11 to 3.12.

  • gh-104263: Fix float("nan") to produce a quiet NaN on platforms (like MIPS) where the meaning of the signalling / quiet bit is inverted from its usual meaning. Also introduce a new macro Py_INFINITY matching C99’s INFINITY, and refactor internals to rely on C99’s NAN and INFINITY macros instead of hard-coding bit patterns for infinities and NaNs. Thanks Sebastian Berg.

  • gh-99113: Multi-phase init extension modules may now indicate that they support running in subinterpreters that have their own GIL. This is done by using Py_MOD_PER_INTERPRETER_GIL_SUPPORTED as the value for the Py_mod_multiple_interpreters module def slot. Otherwise the module, by default, cannot be imported in such subinterpreters. (This does not affect the main interpreter or subinterpreters that do not have their own GIL.) In addition to the isolation that multi-phase init already normally requires, support for per-interpreter GIL involves one additional constraint: thread-safety. If the module has external (linked) dependencies and those libraries have any state that isn’t thread-safe then the module must do the additional work to add thread-safety. This should be an uncommon case.

  • gh-99113: The GIL is now (optionally) per-interpreter. This is the fundamental change for PEP 684. This is all made possible by virtue of the isolated state of each interpreter in the process. The behavior of the main interpreter remains unchanged. Likewise, interpreters created using Py_NewInterpreter() are not affected. To get an interpreter with its own GIL, call Py_NewInterpreterFromConfig().

  • gh-104108: Multi-phase init extension modules may now indicate whether or not they actually support multiple interpreters. By default such modules are expected to support use in multiple interpreters. In the uncommon case that one does not, it may use the new Py_mod_multiple_interpreters module def slot. A value of 0 means the module does not support them. 1 means it does. The default is 1.

  • gh-104142: Fix an issue where list or tuple repetition could fail to respect PEP 683.

  • gh-104078: Improve the performance of PyObject_HasAttrString()

  • gh-104066: Improve the performance of hasattr() for module objects with a missing attribute.

  • gh-104028: Reduce object creation while calling callback function from gc. Patch by Donghee Na.

  • gh-104018: Disallow the “z” format specifier in %-format of bytes objects.

  • gh-102213: Fix performance loss when accessing an object’s attributes with __getattr__ defined.

  • gh-103895: Improve handling of edge cases in showing Exception.__notes__. Ensures that the messages always end with a newline and that string/bytes are not exploded over multiple lines. Patch by Carey Metcalfe.

  • gh-103907: Don’t modify the refcounts of known immortal objects (True, False, and None) in the main interpreter loop.

  • gh-103899: Provide a helpful hint in the TypeError message when accidentally calling a module object that has a callable attribute of the same name (such as dis.dis() or datetime.datetime).

  • gh-103845: Remove both line and instruction instrumentation before adding new ones for monitoring, to avoid newly added instrumentation being removed immediately.

  • gh-103763: Implement PEP 695, adding syntactic support for generic classes, generic functions, and type aliases.

    A new type X = ... syntax is added for type aliases, which resolves at runtime to an instance of the new class typing.TypeAliasType. The value is lazily evaluated and is accessible through the .__value__ attribute. This is implemented as a new AST node ast.TypeAlias.

    New syntax (class X[T]: ..., def func[T](): ...) is added for defining generic functions and classes. This is implemented as a new type_params attribute on the AST nodes for classes and functions. This node holds instances of the new AST classes ast.TypeVar, ast.ParamSpec, and ast.TypeVarTuple.

    typing.TypeVar, typing.ParamSpec, typing.ParamSpecArgs, typing.ParamSpecKwargs, typing.TypeVarTuple, and typing.Generic are now implemented in C rather than Python.

    There are new bytecode instructions LOAD_LOCALS, LOAD_CLASSDICT_OR_GLOBAL, and LOAD_CLASSDICT_OR_DEREF to support correct resolution of names in class namespaces.

    Patch by Eric Traut, Larry Hastings, and Jelle Zijlstra.

Biblioteca

  • gh-103801: Adds three minor linting fixes to the wasm module caught that were caught by ruff.

  • gh-103793: Optimized asyncio Task creation by deferring expensive string formatting (task name generation) from Task creation to the first time get_name is called. This makes asyncio benchmarks up to 5% faster.

Núcleo e embutidos

  • gh-102310: Change the error range for invalid bytes literals.

  • gh-103590: Do not wrap a single exception raised from a try-except* construct in an ExceptionGroup.

  • gh-103650: Change the perf map format to remove the ‘0x’ prefix from the addresses

  • gh-102856: Implement the required C tokenizer changes for PEP 701. Patch by Pablo Galindo Salgado, Lysandros Nikolaou, Batuhan Taskaya, Marta Gómez Macías and sunmy2019.

  • gh-100530: Clarify the error message raised when the called part of a class pattern isn’t actually a class.

  • gh-101517: Fix bug in line numbers of instructions emitted for except*.

  • gh-103492: Clarify SyntaxWarning with literal is comparison by specifying which literal is problematic, since comparisons using is with e.g. None and bool literals are idiomatic.

  • gh-87729: Add LOAD_SUPER_ATTR (and a specialization for super().method()) to speed up super().method() and super().attr. This makes super().method() roughly 2.3x faster and brings it within 20% of the performance of a simple method call. Patch by Vladimir Matveev and Carl Meyer.

  • gh-103488: Change the internal offset distinguishing yield and return target addresses, so that the instruction pointer is correct for exception handling and other stack unwinding.

  • gh-82012: The bitwise inversion operator (~) on bool is deprecated. It returns the bitwise inversion of the underlying int representation such that bool(~True) == True, which can be confusing. Use not for logical negation of bools. In the rare case that you really need the bitwise inversion of the underlying int, convert to int explicitly ~int(x).

  • gh-77757: Exceptions raised in a typeobject’s __set_name__ method are no longer wrapped by a RuntimeError. Context information is added to the exception as a PEP 678 note.

  • gh-103333: AttributeError now retains the name attribute when pickled and unpickled.

  • gh-103242: Migrate set_ecdh_curve() method not to use deprecated OpenSSL APIs. Patch by Donghee Na.

  • gh-103323: We’ve replaced our use of _PyRuntime.tstate_current with a thread-local variable. This is a fairly low-level implementation detail, and there should be no change in behavior.

  • gh-84436: The implementation of PEP-683 which adds Immortal Objects by using a fixed reference count that skips reference counting to make objects truly immutable.

  • gh-102700: Allow built-in modules to be submodules. This allows submodules to be statically linked into a CPython binary.

  • gh-103082: Implement PEP 669 Low Impact Monitoring for CPython.

  • gh-88691: Reduce the number of inline CACHE entries for CALL.

  • gh-102500: Make the buffer protocol accessible in Python code using the new __buffer__ and __release_buffer__ magic methods. See PEP 688 for details. Patch by Jelle Zijlstra.

  • gh-97933: PEP 709: inline list, dict and set comprehensions to improve performance and reduce bytecode size.

  • gh-99184: Bypass instance attribute access of __name__ in repr of weakref.ref.

  • gh-98003: Complex function calls are now faster and consume no C stack space.

  • bpo-39610: len() for 0-dimensional memoryview objects (such as memoryview(ctypes.c_uint8(42))) now raises a TypeError. Previously this returned 1, which was not consistent with mem_0d[0] raising an IndexError.

Biblioteca

  • bpo-31821: Fix pause_reading() to work when called from connection_made() in asyncio.

  • gh-104600: functools.update_wrapper() now sets the __type_params__ attribute (added by PEP 695).

  • gh-104340: When an asyncio pipe protocol loses its connection due to an error, and the caller doesn’t await wait_closed() on the corresponding StreamWriter, don’t log a warning about an exception that was never retrieved. After all, according to the StreamWriter.close() docs, the wait_closed() call is optional (“not mandatory”).

  • gh-104555: Fix issue where an issubclass() check comparing a class X against a runtime-checkable protocol Y with non-callable members would not cause TypeError to be raised if an isinstance() call had previously been made comparing an instance of X to Y. This issue was present in edge cases on Python 3.11, but became more prominent in 3.12 due to some unrelated changes that were made to runtime-checkable protocols. Patch by Alex Waygood.

  • gh-104372: Refactored the _posixsubprocess internals to avoid Python C API usage between fork and exec when marking pass_fds= file descriptors inheritable.

  • gh-104484: Added case_sensitive argument to pathlib.PurePath.match()

  • gh-75367: Fix data descriptor detection in inspect.getattr_static().

  • gh-104536: Fix a race condition in the internal multiprocessing.process cleanup logic that could manifest as an unintended AttributeError when calling process.close().

  • gh-103857: Update datetime deprecations’ stracktrace to point to the calling line

  • gh-101520: Move the core functionality of the tracemalloc module in the Python/ folder, leaving just the module wrapper in Modules/.

  • gh-104392: Remove undocumented and unused _paramspec_tvars attribute from some classes in typing.

  • gh-102613: Fix issue where pathlib.Path.glob() raised RecursionError when walking deep directory trees.

  • gh-103000: Improve performance of dataclasses.asdict() for the common case where dict_factory is dict. Patch by David C Ellis.

  • gh-104301: Allow leading whitespace in disambiguated statements in pdb.

  • gh-104139: Teach urllib.parse.unsplit() to retain the "//" when assembling itms-services://?action=generate-bugs style Apple Platform Deployment URLs.

  • gh-104307: socket.getnameinfo() now releases the GIL while contacting the DNS server

  • gh-104310: Users may now use importlib.util.allowing_all_extensions() (a context manager) to temporarily disable the strict compatibility checks for importing extension modules in subinterpreters.

  • gh-87695: Fix issue where pathlib.Path.glob() raised OSError when it encountered a symlink to an overly long path.

  • gh-104265: Prevent possible crash by disallowing instantiation of the _csv.Reader and _csv.Writer types. The regression was introduced in 3.10.0a4 with PR 23224 (bpo-14935). Patch by Radislav Chugunov.

  • gh-102613: Improve performance of pathlib.Path.glob() when expanding recursive wildcards (”**”) by merging adjacent wildcards and de-duplicating results only when necessary.

  • gh-65772: Remove unneeded comments and code in turtle.py.

  • gh-90208: Fixed issue where pathlib.Path.glob() returned incomplete results when it encountered a PermissionError. This method now suppresses all OSError exceptions, except those raised from calling is_dir() on the top-level path.

  • gh-104144: Optimize asyncio.TaskGroup when using asyncio.eager_task_factory(). Skip scheduling a done callback if a TaskGroup task completes eagerly.

  • gh-104144: Optimize asyncio.gather() when using asyncio.eager_task_factory() to complete eagerly if all fututres completed eagerly. Avoid scheduling done callbacks for futures that complete eagerly.

  • gh-104114: Fix issue where pathlib.Path.glob() returns paths using the case of non-wildcard segments for corresponding path segments, rather than the real filesystem case.

  • gh-104104: Improve performance of pathlib.Path.glob() by using re.IGNORECASE to implement case-insensitive matching.

  • gh-104102: Improve performance of pathlib.Path.glob() when evaluating patterns that contain '../' segments.

  • gh-103822: Update the return type of weekday to the newly added Day attribute

  • gh-103629: Update the repr of typing.Unpack according to PEP 692.

  • gh-103963: Make dis display the names of the args for CALL_INTRINSIC_*.

  • gh-104035: Do not ignore user-defined __getstate__ and __setstate__ methods for slotted frozen dataclasses.

  • gh-103987: In mmap, fix several bugs that could lead to access to memory-mapped files after they have been invalidated.

  • gh-103977: Improve import time of platform module.

  • gh-88773: Added turtle.teleport() to the turtle module to move a turtle to a new point without tracing a line, visible or invisible. Patch by Liam Gersten.

  • gh-103935: Use io.open_code() for files to be executed instead of raw open()

  • gh-68968: Fixed garbled output of assertEqual() when an input lacks final newline.

  • gh-100370: Fix potential OverflowError in sqlite3.Connection.blobopen() for 32-bit builds. Patch by Erlend E. Aasland.

  • gh-102628: Substitute CTRL-D with CTRL-Z in sqlite3 CLI banner when running on Windows.

  • gh-103636: Module-level attributes January and February are deprecated from calendar.

  • gh-103583: Isolate _multibytecodec and codecs extension modules. Patches by Erlend E. Aasland.

  • gh-103848: Add checks to ensure that [ bracketed ] hosts found by urllib.parse.urlsplit() are of IPv6 or IPvFuture format.

  • gh-103872: Update the bundled copy of pip to version 23.1.2.

  • gh-99944: Make dis display the value of oparg of KW_NAMES.

  • gh-74940: The C.UTF-8 locale is no longer converted to en_US.UTF-8, enabling the use of UTF-8 encoding on systems which have no locales installed.

  • gh-103861: Fix zipfile.Zipfile creating invalid zip files when force_zip64 was used to add files to them. Patch by Carey Metcalfe.

  • gh-103857: Deprecated datetime.datetime.utcnow() and datetime.datetime.utcfromtimestamp(). (Patch by Paul Ganssle)

  • gh-103839: Avoid compilation error due to tommath.h not being found when building Tkinter against Tcl 8.7 built with bundled libtommath.

  • gh-103791: contextlib.suppress now supports suppressing exceptions raised as part of an ExceptionGroup. If other exceptions exist on the group, they are re-raised in a group that does not contain the suppressed exceptions.

  • gh-90750: Use datetime.datetime.fromisocalendar() in the implementation of datetime.datetime.strptime(), which should now accept only valid ISO dates. (Patch by Paul Ganssle)

  • gh-103685: Prepare tkinter.Menu.index() for Tk 8.7 so that it does not raise TclError: expected integer but got "" when it should return None.

  • gh-81403: urllib.request.CacheFTPHandler no longer raises URLError if a cached FTP instance is reused. ftplib’s endtransfer method calls voidresp to drain the connection to handle FTP instance reuse properly.

  • gh-103699: Add __orig_bases__ to non-generic TypedDicts, call-based TypedDicts, and call-based NamedTuples. Other TypedDicts and NamedTuples already had the attribute.

  • gh-103693: Add convenience variable feature to pdb

  • gh-92248: Deprecate type, choices, and metavar parameters of argparse.BooleanOptionalAction.

  • gh-89415: Add socket constants for source-specific multicast. Patch by Reese Hyde.

  • gh-103673: socketserver gains ForkingUnixStreamServer and ForkingUnixDatagramServer classes. Patch by Jay Berry.

  • gh-103636: Added Enum for months and days in the calendar module.

  • gh-84976: Create a new Lib/_pydatetime.py file that defines the Python version of the datetime module, and make datetime import the contents of the new library only if the C implementation is missing. Currently, the full Python implementation is defined and then deleted if the C implementation is not available, slowing down import datetime unnecessarily.

  • gh-103596: Attributes/methods are no longer shadowed by same-named enum members, although they may be shadowed by enum.property’s.

  • gh-103584: Updated importlib.metadata with changes from importlib_metadata 5.2 through 6.5.0, including: Support installed-files.txt for Distribution.files when present. PackageMetadata now stipulates an additional get method allowing for easy querying of metadata keys that may not be present. packages_distributions now honors packages and modules with Python modules that not .py sources (e.g. .pyc, .so). Expand protocol for PackageMetadata.get_all to match the upstream implementation of email.message.Message.get_all in python/typeshed#9620. Deprecated use of Distribution without defining abstract methods. Deprecated expectation that PackageMetadata.__getitem__ will return None for missing keys. In the future, it will raise a KeyError.

  • gh-103578: Fixed a bug where pdb crashes when reading source file with different encoding by replacing io.open() with io.open_code(). The new method would also call into the hook set by PyFile_SetOpenCodeHook().

  • gh-103556: Now creating inspect.Signature objects with positional-only parameter with a default followed by a positional-or-keyword parameter without one is impossible.

  • gh-103559: Update the bundled copy of pip to version 23.1.1.

  • gh-103548: Improve performance of pathlib.Path.absolute() and cwd() by joining paths only when necessary. Also improve performance of pathlib.PurePath.is_absolute() on Posix by skipping path parsing and normalization.

  • gh-103538: Remove _tkinter module code guarded by definition of the TK_AQUA macro which was only needed for Tk 8.4.7 or earlier and was never actually defined by any build system or documented for manual use.

  • gh-103533: Update cProfile to use PEP 669 API

  • gh-103525: Fix misleading exception message when mixed str and bytes arguments are supplied to pathlib.PurePath and Path.

  • gh-103489: Add getconfig() and setconfig() to Connection to make configuration changes to a database connection. Patch by Erlend E. Aasland.

  • gh-103365: Set default Flag boundary to STRICT and fix bitwise operations.

  • gh-103472: Avoid a potential ResourceWarning in http.client.HTTPConnection by closing the proxy / tunnel’s CONNECT response explicitly.

  • gh-103462: Fixed an issue with using writelines() in asyncio to send very large payloads that exceed the amount of data that can be written in one call to socket.socket.send() or socket.socket.sendmsg(), resulting in the remaining buffer being left unwritten.

  • gh-103449: Fix a bug in doc string generation in dataclasses.dataclass().

  • gh-103092: Isolate _collections (apply PEP 687). Patch by Erlend E. Aasland.

  • gh-103357: Added support for logging.Formatter defaults parameter to logging.config.dictConfig() and logging.config.fileConfig(). Patch by Bar Harel.

  • gh-103092: Adapt the winreg extension module to PEP 687.

  • gh-74690: The performance of isinstance() checks against runtime-checkable protocols has been considerably improved for protocols that only have a few members. To achieve this improvement, several internal implementation details of the typing module have been refactored, including typing._ProtocolMeta.__instancecheck__, typing._is_callable_members_only, and typing._get_protocol_attrs. Patches by Alex Waygood.

  • gh-74690: The members of a runtime-checkable protocol are now considered “frozen” at runtime as soon as the class has been created. See “What’s new in Python 3.12” for more details.

  • gh-103256: Fixed a bug that caused hmac to raise an exception when the requested hash algorithm was not available in OpenSSL despite being available separately as part of hashlib itself. It now falls back properly to the built-in. This could happen when, for example, your OpenSSL does not include SHA3 support and you want to compute hmac.digest(b'K', b'M', 'sha3_256').

  • gh-102778: Support sys.last_exc in idlelib.

  • gh-103285: Improve performance of ast.get_source_segment().

  • gh-103225: Fix a bug in pdb when displaying line numbers of module-level source code.

  • gh-103092: Adapt the msvcrt extension module to PEP 687.

  • gh-103092: Adapt the winsound extension module to PEP 687.

  • gh-93910: Remove deprecation of enum member.member access.

  • gh-102978: Fixes unittest.mock.patch() not enforcing function signatures for methods decorated with @classmethod or @staticmethod when patch is called with autospec=True.

  • gh-103092: Isolate _socket (apply PEP 687). Patch by Erlend E. Aasland.

  • gh-100479: Add pathlib.PurePath.with_segments(), which creates a path object from arguments. This method is called whenever a derivative path is created, such as from pathlib.PurePath.parent. Subclasses may override this method to share information between path objects.

  • gh-103220: Fix issue where os.path.join() added a slash when joining onto an incomplete UNC drive with a trailing slash on Windows.

  • gh-103204: Fixes http.server accepting HTTP requests with HTTP version numbers preceded by ‘+’, or ‘-’, or with digit-separating ‘_’ characters. The length of the version numbers is also constrained.

  • gh-75586: Fix various Windows-specific issues with shutil.which.

  • gh-103193: Improve performance of inspect.getattr_static(). Patch by Alex Waygood.

  • gh-103176: sys._current_exceptions() now returns a mapping from thread-id to an exception instance, rather than to a (typ, exc, tb) tuple.

  • gh-103143: Polish the help messages and docstrings of pdb.

  • gh-103015: Add entrypoint keyword-only parameter to sqlite3.Connection.load_extension(), for overriding the SQLite extension entry point. Patch by Erlend E. Aasland.

  • gh-103000: Improve performance of dataclasses.astuple() and dataclasses.asdict() in cases where the contents are common Python types.

  • gh-102953: The extraction methods in tarfile, and shutil.unpack_archive(), have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. See Filtros de extração for details.

  • gh-97696: Implemented an eager task factory in asyncio. When used as a task factory on an event loop, it performs eager execution of coroutines. Coroutines that are able to complete synchronously (e.g. return or raise without blocking) are returned immediately as a finished task, and the task is never scheduled to the event loop. If the coroutine blocks, the (pending) task is scheduled and returned.

  • gh-81079: Add case_sensitive keyword-only argument to pathlib.Path.glob() and rglob().

  • gh-101819: Isolate the io extension module by applying PEP 687. Patch by Kumar Aditya, Victor Stinner, and Erlend E. Aasland.

  • gh-91896: Deprecate collections.abc.ByteString

  • gh-101362: Speed up pathlib.Path construction by omitting the path anchor from the internal list of path parts.

  • gh-102114: Functions in the dis module that accept a source code string as argument now print a more concise traceback when the string contains a syntax or indentation error.

  • gh-62432: The unittest runner will now exit with status code 5 if no tests were run. It is common for test runner misconfiguration to fail to find any tests, this should be an error.

  • gh-78079: Fix incorrect normalization of UNC device path roots, and partial UNC share path roots, in pathlib.PurePath. Pathlib no longer appends a trailing slash to such paths.

  • gh-85984: Add tty.cfmakeraw() and tty.cfmakecbreak() to tty and modernize, the behavior of tty.setraw() and tty.setcbreak() to use POSIX.1-2017 Chapter 11 “General Terminal Interface” flag masks by default.

  • gh-101688: Implement types.get_original_bases() to provide further introspection for types.

  • gh-101640: argparse.ArgumentParser now catches errors when writing messages, such as when sys.stderr is None. Patch by Oleg Iarygin.

  • gh-83861: Fix datetime.astimezone method return value when invoked on a naive datetime instance that represents local time falling in a timezone transition gap. PEP 495 requires that instances with fold=1 produce earlier times than those with fold=0 in this case.

  • gh-89550: Decrease execution time of some gzip file writes by 15% by adding more appropriate buffering.

  • gh-95299: Remove the bundled setuptools wheel from ensurepip, and stop installing setuptools in environments created by venv.

  • gh-99353: Respect the http.client.HTTPConnection .debuglevel flag in urllib.request.AbstractHTTPHandler when its constructor parameter debuglevel is not set. And do the same for *HTTPS*.

  • gh-98040: Remove the long-deprecated imp module.

  • gh-97850: Deprecate pkgutil.find_loader() and pkgutil.get_loader() in favor of importlib.util.find_spec().

  • gh-94473: Flatten arguments in tkinter.Canvas.coords(). It now accepts not only x1, y1, x2, y2, ... and [x1, y1, x2, y2, ...], but also (x1, y1), (x2, y2), ... and [(x1, y1), (x2, y2), ...].

  • gh-98040: Remove more deprecated importlib APIs: find_loader(), find_module(), importlib.abc.Finder, pkgutil.ImpImporter, pkgutil.ImpLoader.

  • gh-96522: Fix potential deadlock in pty.spawn()

  • gh-96534: Support divert(4) added in FreeBSD 14.

  • gh-87474: Fix potential file descriptor leaks in subprocess.Popen.

  • gh-94906: Support multiple steps in math.nextafter(). Patch by Shantanu Jain and Matthias Gorgens.

  • gh-51574: Make tempfile.mkdtemp() return absolute paths when its dir parameter is relative.

  • gh-94518: Convert private _posixsubprocess.fork_exec() to use Argument Clinic.

  • gh-92184: When creating zip files using zipfile, os.altsep, if not None, will always be treated as a path separator even when it is not /. Patch by Carey Metcalfe.

  • bpo-46797: Deprecation warnings are now emitted for ast.Num, ast.Bytes, ast.Str, ast.NameConstant and ast.Ellipsis. These have been documented as deprecated since Python 3.8, and will be removed in Python 3.14.

  • bpo-44844: Enables webbrowser to detect and launch Microsoft Edge browser.

  • bpo-45606: Fixed the bug in pathlib.Path.glob() – previously a dangling symlink would not be found by this method when the pattern is an exact match, but would be found when the pattern contains a wildcard or the recursive wildcard (**). With this change, a dangling symlink will be found in both cases.

  • bpo-23041: Add QUOTE_STRINGS and QUOTE_NOTNULL to the suite of csv module quoting styles.

  • bpo-24964: Added http.client.HTTPConnection.get_proxy_response_headers() that provides access to the HTTP headers on a proxy server response to the CONNECT request.

  • bpo-17258: multiprocessing now supports stronger HMAC algorithms for inter-process connection authentication rather than only HMAC-MD5.

  • bpo-39744: Make asyncio.subprocess.Process.communicate() close the subprocess’s stdin even when called with input=None.

  • bpo-22708: http.client CONNECT method tunnel improvements: Use HTTP 1.1 protocol; send a matching Host: header with CONNECT, if one is not provided; convert IDN domain names to Punycode. Patch by Michael Handler.

Documentação

  • gh-67056: Document that the effect of registering or unregistering an atexit cleanup function from within a registered cleanup function is undefined.

  • gh-103629: Mention the new way of typing **kwargs with Unpack and TypedDict introduced in PEP 692.

  • gh-48241: Clarifying documentation about the url parameter to urllib.request.urlopen and urllib.request.Request needing to be encoded properly.

  • gh-86094: Add support for Unicode Path Extra Field in ZipFile. Patch by Yeojin Kim and Andrea Giudiceandrea

  • gh-99202: Fix extension type from documentation for compiling in C++20 mode

Testes

  • gh-104494: Update test_pack_configure_in and test_place_configure_in for changes to error message formatting in Tk 8.7.

  • gh-104461: Run test_configure_screen on X11 only, since the DISPLAY environment variable and -screen option for toplevels are not useful on Tk for Win32 or Aqua.

  • gh-86275: Added property-based tests to the zoneinfo tests, along with stubs for the hypothesis interface. (Patch by Paul Ganssle)

  • gh-103329: Regression tests for the behaviour of unittest.mock.PropertyMock were added.

  • gh-102795: fix use of poll in test_epoll’s test_control_and_wait

  • gh-75729: Fix the os.spawn* tests failing on Windows when the working directory or interpreter path contains spaces.

Construção

  • gh-101282: BOLT optimization is now applied to the libpython shared library if building a shared library. BOLT instrumentation and application settings can now be influenced via the BOLT_INSTRUMENT_FLAGS and BOLT_APPLY_FLAGS configure variables.

  • gh-99017: PYTHON_FOR_REGEN now require Python 3.10 or newer.

  • gh-104490: Define .PHONY / virtual make targets consistently and properly.

  • gh-104106: Add gcc fallback of mkfifoat/mknodat for macOS. Patch by Donghee Na.

  • gh-103532: The TKINTER_PROTECT_LOADTK macro is no longer defined or used in the _tkinter module. It was previously only defined when building against Tk 8.4.13 and older, but Tk older than 8.5.12 has been unsupported since gh-91152.

  • gh-99069: Extended workaround defining static_assert when missing from the libc headers to all clang and gcc builds. In particular, this fixes building on macOS <= 10.10.

  • gh-100220: Changed the default value of the SHELL Makefile variable from /bin/sh to /bin/sh -e to ensure that complex recipes correctly fail after an error. Previously, make install could fail to install some files and yet return a successful result.

  • gh-90656: Add platform triplets for 64-bit LoongArch:

    • loongarch64-linux-gnusf

    • loongarch64-linux-gnuf32

    • loongarch64-linux-gnu

    Patch by Zhang Na.

Windows

  • gh-104623: Update Windows installer to use SQLite 3.42.0.

  • gh-82814: Fix a potential [Errno 13] Permission denied when using shutil.copystat() within Windows Subsystem for Linux (WSL) on a mounted filesystem by adding errno.EACCES to the list of ignored errors within the internal implementation.

  • gh-103088: Fix virtual environment activate script having incorrect line endings for Cygwin.

  • gh-103088: Fixes venvs not working in bash on Windows across different disks

  • gh-102997: Update Windows installer to use SQLite 3.41.2.

  • gh-88013: Fixed a bug where TypeError was raised when calling ntpath.realpath() with a bytes parameter in some cases.

macOS

  • gh-99834: Update macOS installer to Tcl/Tk 8.6.13.

  • gh-104623: Update macOS installer to SQLite 3.42.0.

  • gh-103545: Add os.PRIO_DARWIN_THREAD, os.PRIO_DARWIN_PROCESS, os.PRIO_DARWIN_BG and os.PRIO_DARWIN_NONUI. These can be used with os.setpriority to run the process at a lower priority and make use of the efficiency cores on Apple Silicon systems.

  • gh-104180: Support reading SOCKS proxy configuration from macOS System Configuration. Patch by Sam Schott.

  • gh-60436: update curses textbox to additionally handle backspace using the curses.ascii.DEL key press.

  • gh-102997: Update macOS installer to SQLite 3.41.2.

IDLE

  • gh-104499: Fix completions for Tk Aqua 8.7 (currently blank).

  • gh-104496: About prints both tcl and tk versions if different (expected someday).

  • gh-88496: Fix IDLE test hang on macOS.

Ferramentas/Demos

  • gh-104389: Argument Clinic C converters now accept the unused keyword, for wrapping a parameter with Py_UNUSED. Patch by Erlend E. Aasland.

API C

Python 3.12.0 alpha 7

Data de lançamento: 2023-04-04

Núcleo e embutidos

Biblioteca

Núcleo e embutidos

  • gh-101291: Rearrage bits in first field (after header) of PyLongObject. * Bits 0 and 1: 1 - sign. I.e. 0 for positive numbers, 1 for zero and 2 for negative numbers. * Bit 2 reserved (probably for the immortal bit) * Bits 3+ the unsigned size.

    This makes a few operations slightly more efficient, and will enable a more compact and faster 2s-complement representation of most ints in future.

  • gh-102397: Fix segfault from race condition in signal handling during garbage collection. Patch by Kumar Aditya.

  • gh-102406: codecs encoding/decoding errors now get the context information (which operation and which codecs) attached as PEP 678 notes instead of through chaining a new instance of the exception.

  • gh-102281: Fix potential nullptr dereference and use of uninitialized memory in fileutils. Patch by Max Bachmann.

  • gh-102300: Reuse operands with refcount of 1 in float specializations of BINARY_OP.

  • gh-102213: Fix performance loss when accessing an object’s attributes with __getattr__ defined.

  • gh-102255: Improve build support for the Xbox. Patch by Max Bachmann.

Construção

  • gh-102027: Fix SSE2 and SSE3 detection in _blake2 internal module. Patch by Max Bachmann.

Núcleo e embutidos

  • gh-101865: Deprecate co_lnotab in code objects, schedule it for removal in Python 3.14

Biblioteca

Documentação

Testes

  • gh-102980: Improve test coverage on pdb.

  • gh-102537: Adjust the error handling strategy in test_zoneinfo.TzPathTest.python_tzpath_context. Patch by Paul Ganssle.

  • gh-101377: Improved test_locale_calendar_formatweekday of calendar.

Construção

  • gh-102973: Add a dev container (along with accompanying Dockerfile) for development purposes.

  • gh-102711: Fix -Wstrict-prototypes compiler warnings.

Windows

  • gh-102690: Update webbrowser to fall back to Microsoft Edge instead of Internet Explorer.

  • gh-99726: Improves correctness of stat results for Windows, and uses faster API when available

Ferramentas/Demos

API C

  • gh-102013: Add a new (unstable) C-API function for iterating over GC’able objects using a callback: PyUnstable_VisitObjects.

Python 3.12.0 alpha 6

Data de lançamento: 2023-03-07

Segurança

  • gh-99108: Replace builtin hashlib implementations of MD5 and SHA1 with verified ones from the HACL* project.

  • gh-101727: Updated the OpenSSL version used in Windows and macOS binary release builds to 1.1.1t to address CVE 2023-0286, CVE 2022-4303, and CVE 2022-4303 per the OpenSSL 2023-02-07 security advisory.

  • gh-99108: Replace the builtin hashlib implementations of SHA2-384 and SHA2-512 originally from LibTomCrypt with formally verified, side-channel resistant code from the HACL* project. The builtins remain a fallback only used when OpenSSL does not provide them.

  • gh-101283: subprocess.Popen now uses a safer approach to find cmd.exe when launching with shell=True. Patch by Eryk Sun, based on a patch by Oleg Iarygin.

Núcleo e embutidos

  • gh-102493: Fix regression in semantics of normalisation in PyErr_SetObject.

  • gh-102416: Do not memoize incorrectly automatically generated loop rules in the parser. Patch by Pablo Galindo.

  • gh-102356: Fix a bug that caused a crash when deallocating deeply nested filter objects. Patch by Marta Gómez Macías.

  • gh-102336: Cleanup Windows 7 specific special handling. Patch by Max Bachmann.

  • gh-102250: Fixed a segfault occurring when the interpreter calls a __bool__ method that raises.

  • gh-102126: Fix deadlock at shutdown when clearing thread states if any finalizer tries to acquire the runtime head lock. Patch by Kumar Aditya.

  • gh-102027: Use GetCurrentProcessId on Windows when getpid is unavailable. Patch by Max Bachmann.

  • gh-102056: Fix error handling bugs in interpreter’s exception printing code, which could cause a crash on infinite recursion.

  • gh-100982: Restrict the scope of the FOR_ITER_RANGE instruction to the scope of the original FOR_ITER instruction, to allow instrumentation.

  • gh-101967: Fix possible segfault in positional_only_passed_as_keyword function, when new list created.

  • gh-101952: Fix possible segfault in BUILD_SET opcode, when new set created.

  • gh-74895: socket.getaddrinfo no longer raises OverflowError for int port values outside of the C long range. Out of range values are left up to the underlying string based C library API to report. A socket.gaierror SAI_SERVICE may occur instead, or no error at all as not all platform C libraries generate an error.

  • gh-101799: Add CALL_INTRINSIC_2 and use it instead of PREP_RERAISE_STAR.

  • gh-101857: Fix xattr support detection on Linux systems by widening the check to linux, not just glibc. This fixes support for musl.

  • gh-84783: Make the slice object hashable. Patch by Will Bradshaw and Furkan Onder.

  • gh-87849: Change the SEND instruction to leave the receiver on the stack. This allows the specialized form of SEND to skip the chain of C calls and jump directly to the RESUME in the generator or coroutine.

  • gh-101765: Fix SystemError / segmentation fault in iter __reduce__ when internal access of builtins.__dict__ keys mutates the iter object.

  • gh-101430: Update tracemalloc to handle presize of object properly. Patch by Donghee Na.

  • gh-101696: Invalidate type version tag in _PyStaticType_Dealloc for static types, avoiding bug where a false cache hit could crash the interpreter. Patch by Kumar Aditya.

  • gh-101632: Adds a new RETURN_CONST instruction.

  • gh-100719: Remove gi_code field from generator (and coroutine and async generator) objects as it is redundant. The frame already includes a reference to the code object.

  • gh-98627: When an interpreter is configured to check (and only then), importing an extension module will now fail when the extension does not support multiple interpreters (i.e. doesn’t implement PEP 489 multi-phase init). This does not apply to the main interpreter, nor to subinterpreters created with Py_NewInterpreter().

Biblioteca

Documentação

Testes

  • gh-102019: Fix deadlock on shutdown if test_current_{exception,frames} fails. Patch by Jacob Bower.

  • gh-85984: Utilize new “winsize” functions from termios in pty tests.

  • gh-89792: test_tools now copies up to 10x less source data to a temporary directory during the freeze test by ignoring git metadata and other artifacts. It also limits its python build parallelism based on os.cpu_count instead of hard coding it as 8 cores.

Construção

  • gh-99942: On Android, in a static build, python-config in embed mode no longer incorrectly reports a library to link to.

  • gh-99942: On Android, python.pc now correctly reports the library to link to, the same as python-config.sh.

  • gh-100221: Fix creating install directories in make sharedinstall if they exist outside DESTDIR already.

  • gh-96821: Explicitly mark C extension modules that need defined signed integer overflow, and add a configure option --with-strict-overflow. Patch by Matthias Görgens and Shantanu Jain.

Windows

  • gh-102344: Implement winreg.QueryValue using QueryValueEx and winreg.SetValue using SetValueEx. Patch by Max Bachmann.

  • gh-101881: Handle read and write operations on non-blocking pipes properly on Windows.

  • gh-101881: Add support for the os.get_blocking() and os.set_blocking() functions on Windows.

  • gh-101849: Ensures installer will correctly upgrade existing py.exe launcher installs.

  • gh-101763: Updates copy of libffi bundled with Windows installs to 3.4.4.

  • gh-101759: Update Windows installer to SQLite 3.40.1.

  • gh-101614: Correctly handle extensions built against debug binaries that reference python3_d.dll.

  • gh-101196: The functions os.path.isdir, os.path.isfile, os.path.islink and os.path.exists are now 13% to 28% faster on Windows, by making fewer Win32 API calls.

macOS

  • gh-101759: Update macOS installer to SQLite 3.40.1.

API C

  • gh-101907: Removes use of non-standard C++ extension in public header files.

  • gh-99293: Document that the Py_TPFLAGS_VALID_VERSION_TAG is an internal feature, should not be used, and will be removed.

  • gh-101578: Add PyErr_GetRaisedException() and PyErr_SetRaisedException() for saving and restoring the current exception. These functions return and accept a single exception object, rather than the triple arguments of the now-deprecated PyErr_Fetch() and PyErr_Restore(). This is less error prone and a bit more efficient.

    Add PyException_GetArgs() and PyException_SetArgs() as convenience functions for retrieving and modifying the args passed to the exception’s constructor.

  • gh-91744: Introduced the Unstable C API tier, marking APi that is allowed to change in minor releases without a deprecation period. See PEP 689 for details.

Python 3.12.0 alpha 5

Data de lançamento: 2023-02-07

Segurança

  • gh-99108: Replace the builtin hashlib implementations of SHA2-224 and SHA2-256 originally from LibTomCrypt with formally verified, side-channel resistant code from the HACL* project. The builtins remain a fallback only used when OpenSSL does not provide them.

Núcleo e embutidos

  • gh-92173: Fix the defs and kwdefs arguments to PyEval_EvalCodeEx() and a reference leak in that function.

  • gh-59956: The GILState API is now partially compatible with subinterpreters. Previously, PyThreadState_GET() and PyGILState_GetThisThreadState() would get out of sync, causing inconsistent behavior and crashes.

  • gh-101400: Fix wrong lineno in exception message on continue or break which are not in a loop. Patch by Donghee Na.

  • gh-101372: Fix is_normalized() to properly handle the UCD 3.2.0 cases. Patch by Donghee Na.

  • gh-101266: Fix sys.getsizeof() reporting for int subclasses.

  • gh-101291: Refactor the PyLongObject struct into a normal Python object header and a PyLongValue struct.

  • gh-101046: Fix a possible memory leak in the parser when raising MemoryError. Patch by Pablo Galindo

  • gh-101037: Fix potential memory underallocation issue for instances of int subclasses with value zero.

  • gh-100762: Record the (virtual) exception block depth in the oparg of YIELD_VALUE. Use this to avoid the expensive throw() when closing generators (and coroutines) that can be closed trivially.

  • gh-100982: Adds a new COMPARE_AND_BRANCH instruction. This is a bit more efficient when performing a comparison immediately followed by a branch, and restores the design intent of PEP 659 that specializations are local to a single instruction.

  • gh-100942: Fixed segfault in property.getter/setter/deleter that occurred when a property subclass overrode the __new__ method to return a non-property instance.

  • gh-100923: Remove the mask cache entry for the COMPARE_OP instruction and embed the mask into the oparg.

  • gh-100892: Fix race while iterating over thread states in clearing threading.local. Patch by Kumar Aditya.

  • gh-91351: Fix a case where re-entrant imports could corrupt the import deadlock detection code and cause a KeyError to be raised out of importlib/_bootstrap. In addition to the straightforward cases, this could also happen when garbage collection leads to a warning being emitted – as happens when it collects an open socket or file)

  • gh-100726: Optimize construction of range object for medium size integers.

  • gh-100712: Added option to build cpython with specialization disabled, by setting ENABLE_SPECIALIZATION=False in opcode, followed by make regen-all.

Biblioteca

  • bpo-32780: Inter-field padding is now inserted into the PEP3118 format strings obtained from ctypes.Structure objects, reflecting their true representation in memory.

  • gh-101541: [Enum] - fix psuedo-flag creation

  • gh-101570: Upgrade pip wheel bundled with ensurepip (pip 23.0)

  • gh-101323: Fix a bug where errors where not thrown by zlib._ZlibDecompressor if encountered during decompressing.

  • gh-101317: Add ssl_shutdown_timeout parameter for asyncio.StreamWriter.start_tls().

  • gh-101326: Fix regression when passing None as second or third argument to FutureIter.throw.

  • gh-92123: Adapt the _elementtree extension module to multi-phase init (PEP 489). Patches by Erlend E. Aasland.

  • gh-100795: Avoid potential unexpected freeaddrinfo call (double free) in socket when a libc getaddrinfo() implementation leaves garbage in an output pointer when returning an error. Original patch by Sergey G. Brester.

  • gh-101143: Remove unused references to TimerHandle in asyncio.base_events.BaseEventLoop._add_callback.

  • gh-101144: Make zipfile.Path.open() and zipfile.Path.read_text() also accept encoding as a positional argument. This was the behavior in Python 3.9 and earlier. 3.10 introduced a regression where supplying it as a positional argument would lead to a TypeError.

  • gh-94518: Group-related variables of _posixsubprocess module are renamed to stress that supplementary group affinity is added to a fork, not replace the inherited ones. Patch by Oleg Iarygin.

  • gh-101015: Fix typing.get_type_hints() on '*tuple[...]' and *tuple[...]. It must not drop the Unpack part.

  • gh-101000: Add os.path.splitroot(), which splits a path into a 3-item tuple (drive, root, tail). This new function is used by pathlib to improve the performance of path construction by up to a third.

  • gh-100573: Fix a Windows asyncio bug with named pipes where a client doing os.stat() on the pipe would cause an error in the server that disabled serving future requests.

  • gh-39615: warnings.warn() now has the ability to skip stack frames based on code filename prefix rather than only a numeric stacklevel via the new skip_file_prefixes keyword argument.

  • gh-100750: pass encoding kwarg to subprocess in platform

  • gh-100160: Emit a deprecation warning in asyncio.DefaultEventLoopPolicy.get_event_loop() if there is no current event loop set and it decides to create one.

  • gh-96290: Fix handling of partial and invalid UNC drives in ntpath.splitdrive(), and in ntpath.normpath() on non-Windows systems. Paths such as ‘\server’ and ‘\’ are now considered by splitdrive() to contain only a drive, and consequently are not modified by normpath() on non-Windows systems. The behaviour of normpath() on Windows systems is unaffected, as native OS APIs are used. Patch by Eryk Sun, with contributions by Barney Gale.

  • gh-99952: Fix a reference undercounting issue in ctypes.Structure with from_param() results larger than a C pointer.

  • gh-67790: Add float-style formatting support for fractions.Fraction instances.

  • gh-99266: Preserve more detailed error messages in ctypes.

  • gh-86682: Ensure runtime-created collections have the correct module name using the newly added (internal) sys._getframemodulename().

  • gh-88597: uuid now has a command line interface. Try python -m uuid -h.

  • gh-60580: ctypes.wintypes.BYTE definition changed from c_byte to c_ubyte to match Windows SDK. Patch by Anatoly Techtonik and Oleg Iarygin.

  • gh-94518: _posixsubprocess now initializes all UID and GID variables using a reserved -1 value instead of a separate flag. Patch by Oleg Iarygin.

  • bpo-38941: The xml.etree.ElementTree module now emits DeprecationWarning when testing the truth value of an xml.etree.ElementTree.Element. Before, the Python implementation emitted FutureWarning, and the C implementation emitted nothing.

  • bpo-40077: Convert elementtree types to heap types. Patch by Erlend E. Aasland.

  • bpo-29847: Fix a bug where pathlib.Path accepted and ignored keyword arguments. Patch provided by Yurii Karabas.

  • gh-77772: ctypes.CDLL, ctypes.OleDLL, ctypes.WinDLL, and ctypes.PyDLL now accept path-like objects as their name argument. Patch by Robert Hoelzl.

Documentação

  • gh-88324: Reword subprocess to emphasize default behavior of stdin, stdout, and stderr arguments. Remove inaccurate statement about child file handle inheritance.

Testes

  • gh-101334: test_tarfile has been updated to pass when run as a high UID.

Construção

  • gh-101282: Update BOLT configuration not to use deprecated usage of --split functions. Patch by Donghee Na.

  • gh-101522: Allow overriding Windows dependencies versions and paths using MSBuild properties.

  • gh-77532: Minor fixes to allow building with PlatformToolset=ClangCL on Windows.

  • gh-101152: In accordance with PEP 699, the ma_version_tag field in PyDictObject is deprecated for extension modules. Accessing this field will generate a compiler warning at compile time. This field will be removed in Python 3.14.

  • gh-100340: Allows -Wno-int-conversion for wasm-sdk 17 and onwards, thus enables building WASI builds once against the latest sdk.

  • gh-101060: Conditionally add -fno-reorder-blocks-and-partition in configure. Effectively fixes --enable-bolt when using Clang, as this appears to be a GCC-only flag.

  • gh-98705: __bool__ is defined in AIX system header files which breaks the build in AIX, so undefine it.

  • gh-98636: Fix a regression in detecting gdbm_compat library for the _gdbm module build.

  • gh-96305: _aix_support now uses a simple code to get platform details rather than the now non-existent _bootsubprocess during bootstrap.

Windows

  • gh-101543: Ensure the install path in the registry is only used when the standard library hasn’t been located in any other way.

  • gh-101467: The py.exe launcher now correctly filters when only a single runtime is installed. It also correctly handles prefix matches on tags so that -3.1 does not match 3.11, but would still match 3.1-32.

  • gh-99834: Updates bundled copy of Tcl/Tk to 8.6.13.0

  • gh-101135: Restore ability to launch older 32-bit versions from the py.exe launcher when both 32-bit and 64-bit installs of the same version are available.

  • gh-82052: Fixed an issue where writing more than 32K of Unicode output to the console screen in one go can result in mojibake.

  • gh-100320: Ensures the PythonPath registry key from an install is used when launching from a different copy of Python that relies on an existing install to provide a copy of its modules and standard library.

  • gh-100247: Restores support for the py.exe launcher finding shebang commands in its configuration file using the full command name.

Python 3.12.0 alpha 4

Data de lançamento: 2023-01-10

Núcleo e embutidos

  • gh-100776: Fix misleading default value in input()’s __text_signature__.

  • gh-99005: Remove UNARY_POSITIVE, ASYNC_GEN_WRAP and LIST_TO_TUPLE, replacing them with intrinsics.

  • gh-99005: Add new CALL_INTRINSIC_1 instruction. Remove IMPORT_STAR, PRINT_EXPR and STOPITERATION_ERROR, replacing them with the CALL_INTRINSIC_1 instruction.

  • gh-100288: Remove the LOAD_ATTR_METHOD_WITH_DICT specialized instruction. Stats show it is not useful.

  • gh-100720: Added _PyFrame_NumSlotsForCodeObject, which returns the number of slots needed in a frame for a given code object.

  • gh-100719: Removed the co_nplaincellvars field from the code object, as it is redundant.

  • gh-100637: Fix int.__sizeof__() calculation to include the 1-element ob_digit array for 0 and False.

  • gh-100649: Update the native_thread_id field of PyThreadState after fork.

  • gh-100126: Fix an issue where “incomplete” frames could be briefly visible to C code while other frames are being torn down, possibly resulting in corruption or hard crashes of the interpreter while running finalizers.

  • gh-87447: Fix SyntaxError on comprehension rebind checking with names that are not actually redefined.

    Now reassigning b in [(b := 1) for a, b.prop in some_iter] is allowed. Reassigning a is still disallowed as per PEP 572.

  • gh-100268: Add int.is_integer() to improve duck type compatibility between int and float.

  • gh-100425: Improve the accuracy of sum() with compensated summation.

Biblioteca

Núcleo e embutidos

  • gh-100357: Convert vars, dir, next, getattr, and iter to argument clinic.

  • gh-100117: Improve the output of codeobject.co_lines() by emitting only one entry for each line range.

  • gh-90043: Handle NaNs when specializing COMPARE_OP for float values.

  • gh-100222: Redefine the _Py_CODEUNIT typedef as a union to describe its layout to the C compiler, avoiding type punning and improving clarity.

  • gh-99955: Internal compiler functions (in compile.c) now consistently return -1 on error and 0 on success.

  • gh-100188: The BINARY_SUBSCR_LIST_INT and BINARY_SUBSCR_TUPLE_INT instructions are no longer used for negative integers because those instructions always miss when encountering negative integers.

  • gh-99110: Initialize frame->previous in frameobject.c to fix a segmentation fault when accessing frames created by PyFrame_New().

  • gh-94155: Improved the hashing algorithm for code objects, mitigating some hash collisions.

  • gh-99540: None now hashes to a constant value. This is not a requirements change.

  • gh-100143: When built with --enable-pystats, stats collection is now off by default. To enable it early at startup, pass the -Xpystats flag. Stats are now always dumped, even if switched off.

  • gh-100146: Improve BUILD_LIST opcode so that it works similarly to the BUILD_TUPLE opcode, by stealing references from the stack rather than repeatedly using stack operations to set list elements. Implementation details are in a new private API _PyList_FromArraySteal().

  • gh-100110: Specialize FOR_ITER for tuples.

  • gh-100050: Honor existing errors obtained when searching for mismatching parentheses in the tokenizer. Patch by Pablo Galindo

  • gh-92216: Improve the performance of hasattr() for type objects with a missing attribute.

  • gh-99582: Freeze zipimport module into _bootstrap_python.

  • gh-99554: Pack debugging location tables more efficiently during bytecode compilation.

  • gh-98522: Add an internal version number to code objects, to give better versioning of inner functions and comprehensions, and thus better specialization of those functions. This change is invisible to both Python and C extensions.

  • gh-94603: Improve performance of list.pop for small lists.

Biblioteca

Núcleo e embutidos

  • bpo-32782: ctypes arrays of length 0 now report a correct itemsize when a memoryview is constructed from them, rather than always giving a value of 0.

Biblioteca

  • gh-100833: Speed up math.fsum() by removing defensive volatile qualifiers.

  • gh-100805: Modify random.choice() implementation to once again work with NumPy arrays.

  • gh-100813: Add socket.IP_PKTINFO constant.

  • gh-100792: Make email.message.Message.__contains__() twice as fast.

  • gh-91851: Microoptimizations for fractions.Fraction.__round__(), fractions.Fraction.__ceil__() and fractions.Fraction.__floor__().

  • gh-90104: Avoid RecursionError on repr if a dataclass field definition has a cyclic reference.

  • gh-100689: Fix crash in pyexpat by statically allocating PyExpat_CAPI capsule.

  • gh-100740: Fix unittest.mock.Mock not respecting the spec for attribute names prefixed with assert.

  • gh-91219: Change SimpleHTTPRequestHandler to support subclassing to provide a different set of index file names instead of using __init__ parameters.

  • gh-100690: Mock objects which are not unsafe will now raise an AttributeError when accessing an attribute that matches the name of an assertion but without the prefix assert_, e.g. accessing called_once instead of assert_called_once. This is in addition to this already happening for accessing attributes with prefixes assert, assret, asert, aseert, and assrt.

  • gh-89727: Simplify and optimize os.walk() by using isinstance() checks to check the top of the stack.

  • gh-100485: Add math.sumprod() to compute the sum of products.

  • gh-86508: Fix asyncio.open_connection() to skip binding to local addresses of different family. Patch by Kumar Aditya.

  • gh-97930: importlib.resources.files now accepts a module as an anchor instead of only accepting packages. If a module is passed, resources are resolved adjacent to that module (in the same package or at the package root). The parameter was renamed from package to anchor with a compatibility shim for those passing by keyword. Additionally, the new anchor parameter is now optional and will default to the caller’s module.

  • gh-100585: Fixed a bug where importlib.resources.as_file was leaving file pointers open

  • gh-100562: Improve performance of pathlib.Path.absolute() by nearly 2x. This comes at the cost of a performance regression in pathlib.Path.cwd(), which is generally used less frequently in user code.

  • gh-100519: Small simplification of http.cookiejar.eff_request_host() that improves readability and better matches the RFC wording.

  • gh-100287: Fix the interaction of unittest.mock.seal() with unittest.mock.AsyncMock.

  • gh-100488: Add Fraction.is_integer() to check whether a fractions.Fraction is an integer. This improves duck type compatibility with float and int.

  • gh-100474: http.server now checks that an index page is actually a regular file before trying to serve it. This avoids issues with directories named index.html.

  • gh-100363: Speed up asyncio.get_running_loop() by removing redundant getpid checks. Patch by Kumar Aditya.

  • gh-78878: Fix crash when creating an instance of _ctypes.CField.

  • gh-100348: Fix ref cycle in asyncio._SelectorSocketTransport by removing _read_ready_cb in close.

  • gh-100344: Provide C implementation for asyncio.current_task() for a 4x-6x speedup.

  • gh-100272: Fix JSON serialization of OrderedDict. It now preserves the order of keys.

  • gh-83076: Instantiation of Mock() and AsyncMock() is now 3.8x faster.

  • gh-100234: Set a default value of 1.0 for the lambd parameter in random.expovariate().

  • gh-100228: A DeprecationWarning may be raised when os.fork() or os.forkpty() is called from multi-threaded processes. Forking with threads is unsafe and can cause deadlocks, crashes and subtle problems. Lack of a warning does not indicate that the fork call was actually safe, as Python may not be aware of all threads.

  • gh-100039: Improve signatures for enums and flags.

  • gh-100133: Fix regression in asyncio where a subprocess would sometimes lose data received from pipe.

  • bpo-44592: Fixes inconsistent handling of case sensitivity of extrasaction arg in csv.DictWriter.

  • gh-100098: Fix tuple subclasses being cast to tuple when used as enum values.

  • gh-85432: Rename the fmt parameter of the pure-Python implementation of datetime.time.strftime() to format. Rename the t parameter of datetime.datetime.fromtimestamp() to timestamp. These changes mean the parameter names in the pure-Python implementation now match the parameter names in the C implementation. Patch by Alex Waygood.

  • gh-98778: Update HTTPError to be initialized properly, even if the fp is None. Patch by Donghee Na.

  • gh-99925: Unify error messages in JSON serialization between json.dumps(float('nan'), allow_nan=False) and json.dumps(float('nan'), allow_nan=False, indent=<SOMETHING>). Now both include the representation of the value that could not be serialized.

  • gh-89727: Fix issue with os.walk() where a RecursionError would occur on deep directory structures by adjusting the implementation of os.walk() to be iterative instead of recursive.

  • gh-94943: Add Suporte a dataclass to the Enum __repr__(). When inheriting from a dataclass, only show the field names in the value section of the member repr(), and not the dataclass’ class name.

  • gh-83035: Fix inspect.getsource() handling of decorator calls with nested parentheses.

  • gh-99576: Fix .save() method for LWPCookieJar and MozillaCookieJar: saved file was not truncated on repeated save.

  • gh-94912: Add inspect.markcoroutinefunction() decorator which manually marks a function as a coroutine for the benefit of iscoroutinefunction().

  • gh-99509: Add PEP 585 support for multiprocessing.queues.Queue.

  • gh-99482: Remove Jython partial compatibility code from several stdlib modules.

  • gh-99433: Fix doctest failure on types.MethodWrapperType in modules.

  • gh-85267: Several improvements to inspect.signature()’s handling of __text_signature. - Fixes a case where inspect.signature() dropped parameters - Fixes a case where inspect.signature() raised tokenize.TokenError - Allows inspect.signature() to understand defaults involving binary operations of constants - inspect.signature() is documented as only raising TypeError or ValueError, but sometimes raised RuntimeError. These cases now raise ValueError - Removed a dead code path

  • gh-91166: asyncio is optimized to avoid excessive copying when writing to socket and use sendmsg() if the platform supports it. Patch by Kumar Aditya.

  • gh-98030: Add missing TCP socket options from Linux: TCP_MD5SIG, TCP_THIN_LINEAR_TIMEOUTS, TCP_THIN_DUPACK, TCP_REPAIR, TCP_REPAIR_QUEUE, TCP_QUEUE_SEQ, TCP_REPAIR_OPTIONS, TCP_TIMESTAMP, TCP_CC_INFO, TCP_SAVE_SYN, TCP_SAVED_SYN, TCP_REPAIR_WINDOW, TCP_FASTOPEN_CONNECT, TCP_ULP, TCP_MD5SIG_EXT, TCP_FASTOPEN_KEY, TCP_FASTOPEN_NO_COOKIE, TCP_ZEROCOPY_RECEIVE, TCP_INQ, TCP_TX_DELAY.

  • gh-88500: Reduced the memory usage of urllib.parse.unquote() and urllib.parse.unquote_to_bytes() on large values.

  • gh-96127: inspect.signature was raising TypeError on call with mock objects. Now it correctly returns (*args, **kwargs) as inferred signature.

  • gh-95882: Fix a 3.11 regression in asynccontextmanager(), which caused it to propagate exceptions with incorrect tracebacks and fix a 3.11 regression in contextmanager(), which caused it to propagate exceptions with incorrect tracebacks for StopIteration.

  • gh-78707: Deprecate passing more than one positional argument to pathlib.PurePath.relative_to() and is_relative_to().

  • gh-92122: Fix reStructuredText syntax errors in docstrings in the enum module.

  • gh-91851: Optimize the Fraction arithmetics for small components.

  • bpo-24132: Make pathlib.PurePath and Path subclassable (private to start). Previously, attempting to instantiate a subclass resulted in an AttributeError being raised. Patch by Barney Gale.

  • bpo-40447: Accept os.PathLike (such as pathlib.Path) in the stripdir arguments of compileall.compile_file() and compileall.compile_dir().

  • bpo-36880: Fix a reference counting issue when a ctypes callback with return type py_object returns None, which could cause crashes.

Documentação

Testes

  • gh-100454: Start running SSL tests with OpenSSL 3.1.0-beta1.

  • gh-100086: The Python test runner (libregrtest) now logs Python build information like “debug” vs “release” build, or LTO and PGO optimizations. Patch by Victor Stinner.

  • gh-93018: Make two tests forgiving towards host system libexpat with backported security fixes applied.

Construção

  • gh-100540: Removed the --with-system-ffi configure option; libffi must now always be supplied by the system on all non-Windows platforms. The option has had no effect on non-Darwin platforms for several releases, and in 3.11 only had the non-obvious effect of invoking pkg-config to find libffi and never setting -DUSING_APPLE_OS_LIBFFI. Now on Darwin platforms configure will first check for the OS libffi and then fall back to the same processing as other platforms if it is not found.

  • gh-88267: Avoid exporting Python symbols in linked Windows applications when the core is built as static.

  • bpo-41916: Allow override of ac_cv_cxx_thread so that cross compiled python can set -pthread for CXX.

Windows

  • gh-100180: Update Windows installer to OpenSSL 1.1.1s

  • gh-99191: Use _MSVC_LANG >= 202002L instead of less-precise _MSC_VER >=1929 to more accurately test for C++20 support in PC/_wmimodule.cpp.

  • gh-79218: Define MS_WIN64 for Mingw-w64 64bit, fix cython compilation failure.

  • gh-99941: Ensure that asyncio.Protocol.data_received() receives an immutable bytes object (as documented), instead of bytearray.

  • bpo-43984: winreg.SetValueEx() now leaves the target value untouched in the case of conversion errors. Previously, -1 would be written in case of such errors.

  • bpo-34816: hasattr(ctypes.windll, 'nonexistant') now returns False instead of raising OSError.

macOS

  • gh-100180: Update macOS installer to OpenSSL 1.1.1s

  • gh-100540: Removed obsolete dlfcn.h shim from the _ctypes extension module, which has not been necessary since Mac OS X 10.2.

Ferramentas/Demos

  • bpo-45256: Fix a bug that caused an AttributeError to be raised in python-gdb.py when py-locals is used without a frame.

  • gh-100342: Add missing NULL check for possible allocation failure in *args parsing in Argument Clinic.

API C

  • gh-99947: Raising SystemError on import will now have its cause be set to the original unexpected exception.

  • gh-99240: In argument parsing, after deallocating newly allocated memory, reset its pointer to NULL.

  • gh-98724: The Py_CLEAR, Py_SETREF and Py_XSETREF macros now only evaluate their arguments once. If an argument has side effects, these side effects are no longer duplicated. Patch by Victor Stinner.

Python 3.12.0 alpha 3

Data de lançamento: 2022-12-06

Segurança

  • gh-100001: python -m http.server no longer allows terminal control characters sent within a garbage request to be printed to the stderr server log.

    This is done by changing the http.server BaseHTTPRequestHandler .log_message method to replace control characters with a \xHH hex escape before printing.

  • gh-87604: Avoid publishing list of active per-interpreter audit hooks via the gc module

Núcleo e embutidos

  • gh-99891: Fix a bug in the tokenizer that could cause infinite recursion when showing syntax warnings that happen in the first line of the source. Patch by Pablo Galindo

  • gh-91054: Add PyCode_AddWatcher() and PyCode_ClearWatcher() APIs to register callbacks to receive notification on creation and destruction of code objects.

  • gh-99729: Fix an issue that could cause frames to be visible to Python code as they are being torn down, possibly leading to memory corruption or hard crashes of the interpreter.

  • gh-99708: Fix bug where compiler crashes on an if expression with an empty body block.

  • gh-99578: Fix a reference bug in _imp.create_builtin() after the creation of the first sub-interpreter for modules builtins and sys. Patch by Victor Stinner.

  • gh-99581: Fixed a bug that was causing a buffer overflow if the tokenizer copies a line missing the newline character from a file that is as long as the available tokenizer buffer. Patch by Pablo galindo

  • gh-99553: Fix bug where an ExceptionGroup subclass can wrap a BaseException.

Biblioteca

  • gh-99547: Add a function to os.path to check if a path is a junction: isjunction. Add similar functionality to pathlib.Path as is_junction.

  • gh-99370: Fix zip path for venv created from a non-installed python on POSIX platforms.

Núcleo e embutidos

  • gh-99377: Add audit events for thread creation and clear operations.

  • gh-98686: Remove the BINARY_OP_GENERIC and COMPARE_OP_GENERIC “specializations”.

  • gh-99298: Remove the remaining error paths for attribute specializations, and refuse to specialize attribute accesses on types that haven’t had PyType_Ready() called on them yet.

  • gh-99127: Allow some features of syslog to the main interpreter only. Patch by Donghee Na.

  • gh-91053: Optimizing interpreters and JIT compilers may need to invalidate internal metadata when functions are modified. This change adds the ability to provide a callback that will be invoked each time a function is created, modified, or destroyed.

  • gh-90994: Improve error messages when there’s a syntax error with call arguments. The following three cases are covered: - No value is assigned to a named argument, eg foo(a=). - A value is assigned to a star argument, eg foo(*args=[0]). - A value is assigned to a double-star keyword argument, eg foo(**kwarg={'a': 0}).

  • bpo-45026: Optimize the range object iterator. It is now smaller, faster iteration of ranges containing large numbers. Smaller pickles, faster unpickling.

  • bpo-31718: Raise ValueError instead of SystemError when methods of uninitialized io.IncrementalNewlineDecoder objects are called. Patch by Oren Milman.

  • bpo-38031: Fix a possible assertion failure in io.FileIO when the opener returns an invalid file descriptor.

Biblioteca

  • gh-100001: Also escape s in the http.server BaseHTTPRequestHandler.log_message so that it is technically possible to parse the line and reconstruct what the original data was. Without this a xHH is ambiguous as to if it is a hex replacement we put in or the characters r”x” came through in the original request line.

  • gh-99957: Add frozen_default parameter to typing.dataclass_transform().

  • gh-79033: Fix asyncio.Server.wait_closed() to actually do what the docs promise – wait for all existing connections to complete, after closing the server.

  • gh-51524: Fix bug when calling trace.CoverageResults with valid infile.

  • gh-99645: Fix a bug in handling class cleanups in unittest.TestCase. Now addClassCleanup() uses separate lists for different TestCase subclasses, and doClassCleanups() only cleans up the particular class.

  • gh-99508: Fix TypeError in Lib/importlib/_bootstrap_external.py while calling _imp.source_hash().

  • gh-66285: Fix asyncio to not share event loop and signal wakeupfd in forked processes. Patch by Kumar Aditya.

  • gh-97001: Release the GIL when calling termios APIs to avoid blocking threads.

  • gh-92647: Use final status of an enum to determine lookup or creation branch of functional API.

  • gh-99388: Add loop_factory parameter to asyncio.run() to allow specifying a custom event loop factory. Patch by Kumar Aditya.

  • gh-99341: Fix ast.increment_lineno() to also cover ast.TypeIgnore when changing line numbers.

  • gh-99382: Check the number of arguments in substitution in user generics containing a TypeVarTuple and one or more TypeVar.

  • gh-99379: Fix substitution of ParamSpec followed by TypeVarTuple in generic aliases.

  • gh-99344: Fix substitution of TypeVarTuple and ParamSpec together in user generics.

  • gh-99284: Remove _use_broken_old_ctypes_structure_semantics_ old untested and undocumented hack from ctypes.

  • gh-99201: Fix IndexError when initializing the config variables on Windows if HAVE_DYNAMIC_LOADING is not set.

  • gh-99240: Fix double-free bug in Argument Clinic str_converter by extracting memory clean up to a new post_parsing section.

  • gh-64490: Fix refcount error when arguments are packed to tuple in Argument Clinic.

  • gh-99029: pathlib.PurePath.relative_to() now treats naked Windows drive paths as relative. This brings its behaviour in line with other parts of pathlib.

  • gh-98253: The implementation of the typing module is now more resilient to reference leaks in binary extension modules.

    Previously, a reference leak in a typed C API-based extension module could leak internals of the typing module, which could in turn introduce leaks in essentially any other package with typed function signatures. Although the typing package is not the original source of the problem, such non-local dependences exacerbate debugging of large-scale projects, and the implementation was therefore changed to reduce harm by providing better isolation.

  • gh-98458: Fix infinite loop in unittest when a self-referencing chained exception is raised

  • gh-93453: asyncio.get_event_loop() and many other asyncio functions like asyncio.ensure_future(), asyncio.shield() or asyncio.gather(), and also the get_event_loop() method of asyncio.BaseDefaultEventLoopPolicy now raise a RuntimeError if called when there is no running event loop and the current event loop was not set. Previously they implicitly created and set a new current event loop. DeprecationWarning is no longer emitted if there is no running event loop but the current event loop was set.

  • gh-97966: On os.uname_result, restored expectation that _fields and _asdict would include all six properties including processor.

  • gh-98248: Provide informative error messages in struct.pack() when its integral arguments are not in range.

  • gh-98108: zipfile.Path is now pickleable if its initialization parameters were pickleable (e.g. for file system paths).

  • gh-98098: Created packages from zipfile and test_zipfile modules, separating zipfile.Path functionality.

  • gh-82836: Fix is_private properties in the ipaddress module. Previously non-private networks (0.0.0.0/0) would return True from this method; now they correctly return False.

  • gh-96828: Add an OP_ENABLE_KTLS option for enabling the use of the kernel TLS (kTLS). Patch by Illia Volochii.

  • gh-88863: To avoid apparent memory leaks when asyncio.open_connection() raises, break reference cycles generated by local exception and future instances (which has exception instance as its member var). Patch by Dong Uk, Kang.

  • gh-91078: TarFile.next() now returns None when called on an empty tarfile.

  • bpo-47220: Document the optional callback parameter of WeakMethod. Patch by Géry Ogam.

  • bpo-44817: Ignore WinError 53 (ERROR_BAD_NETPATH), 65 (ERROR_NETWORK_ACCESS_DENIED) and 161 (ERROR_BAD_PATHNAME) when using ntpath.realpath().

  • bpo-41260: Rename the fmt parameter of the pure Python implementation of datetime.date.strftime() to format.

  • bpo-15999: All built-in functions now accept arguments of any type instead of just bool and int for boolean parameters.

Documentação

  • gh-99931: Use sphinxext-opengraph to generate OpenGraph metadata.

  • gh-89682: Reworded docstring of the default __contains__ to clarify that it returns a bool.

  • gh-88330: Improved the description of what a resource is in importlib.resources docs.

  • gh-92892: Document that calling variadic functions with ctypes requires special care on macOS/arm64 (and possibly other platforms).

  • bpo-41825: Restructured the documentation for the os.wait* family of functions, and improved the docs for os.waitid() with more explanation of the possible argument constants.

Testes

  • gh-99892: Skip test_normalization() of test_unicodedata if it fails to download NormalizationTest.txt file from pythontest.net. Patch by Victor Stinner.

  • gh-99934: Correct test_marsh on (32 bit) x86: test_deterministic sets was failing.

  • gh-99741: We’ve implemented multi-phase init (PEP 489/630/687) for the internal (for testing) _xxsubinterpreters module.

  • gh-99659: Optional big memory tests in test_sqlite3 now catch the correct sqlite.DataError exception type in case of too large strings and/or blobs passed.

  • gh-99593: Cover the Unicode C API with tests.

  • gh-96002: Add functional test for Argument Clinic.

Construção

  • gh-99086: Fix -Wimplicit-int, -Wstrict-prototypes, and -Wimplicit-function-declaration compiler warnings in configure checks.

  • gh-99337: Fix a compilation issue with GCC 12 on macOS.

  • gh-99289: Add a COMPILEALL_OPTS variable in Makefile to override compileall options (default: -j0) in make install. Also merged the compileall commands into a single command building .pyc files for the all optimization levels (0, 1, 2) at once. Patch by Victor Stinner.

  • gh-98872: Fix a possible fd leak in Programs/_freeze_module.c introduced in Python 3.11.

  • gh-88226: Always define TARGET_* labels in Python/ceval.c, even if USE_COMPUTED_GOTOS is disabled. This allows breakpoints to be set at those labels in (for instance) gdb.

Windows

macOS

  • gh-87235: On macOS python3 /dev/fd/9 9</path/to/script.py failed for any script longer than a couple of bytes.

  • gh-98940: Fix Mac/Extras.install.py file filter bug.

Ferramentas/Demos

  • gh-64490: Argument Clinic varargs bugfixes

    • Fix out-of-bounds error in _PyArg_UnpackKeywordsWithVararg().

    • Fix incorrect check which allowed more than one varargs in clinic.py.

    • Fix miscalculation of noptargs in generated code.

    • Do not generate noptargs when there is a vararg argument and no optional argument.

API C

  • gh-98680: PyBUF_* constants were marked as part of Limited API of Python 3.11+. These were available in 3.11.0 with Py_LIMITED_API defined for 3.11, and are necessary to use the buffer API.

  • gh-99612: Fix PyUnicode_DecodeUTF8Stateful() for ASCII-only data: *consumed was not set.

  • gh-47146: The structmember.h header is deprecated. Its non-deprecated contents are now available just by including Python.h, with a Py_ prefix added if it was missing. (Deprecated contents are T_OBJECT, T_NONE, and no-op flags.) Patch by Petr Viktorin, based on earlier work by Alexander Belopolsky and Matthias Braun.

Python 3.12.0 alpha 2

Data de lançamento: 2022-11-14

Segurança

  • gh-98433: The IDNA codec decoder used on DNS hostnames by socket or asyncio related name resolution functions no longer involves a quadratic algorithm. This prevents a potential CPU denial of service if an out-of-spec excessive length hostname involving bidirectional characters were decoded. Some protocols such as urllib http 3xx redirects potentially allow for an attacker to supply such a name.

    Individual labels within an IDNA encoded DNS name will now raise an error early during IDNA decoding if they are longer than 1024 unicode characters given that each decoded DNS label must be 63 or fewer characters and the entire decoded DNS name is limited to 255. Only an application presenting a hostname or label consisting primarily of RFC 3454 section 3.1 “Nothing” characters to be removed would run into of this new limit. See also RFC 5894 section 6 and RFC 3491.

  • gh-98739: Update bundled libexpat to 2.5.0

Núcleo e embutidos

  • gh-81057: The docs clearly say that PyImport_Inittab, PyImport_AppendInittab(), and PyImport_ExtendInittab() should not be used after Py_Initialize() has been called. We now enforce this for the two functions. Additionally, the runtime now uses an internal copy of PyImport_Inittab, to guard against modification.

  • gh-99298: Fix an issue that could potentially cause incorrect error handling for some bytecode instructions.

  • gh-99254: The compiler now removes all unused constants from code objects (except the first one, which may be a docstring).

  • gh-99205: Fix an issue that prevented PyThreadState and PyInterpreterState memory from being freed properly.

  • gh-81057: The 18 global C variables holding the state of the allocators have been moved to _PyRuntimeState. This is a strictly internal change with no change in behavior.

  • gh-99181: Fix failure in except* with unhashable exceptions.

  • gh-99204: Fix calculation of sys._base_executable when inside a POSIX virtual environment using copies of the python binary when the base installation does not provide the executable name used by the venv. Calculation will fall back to alternative names (“python<MAJOR>”, “python<MAJOR>.<MINOR>”).

  • gh-96055: Update faulthandler to emit an error message with the proper unexpected signal number. Patch by Donghee Na.

  • gh-99153: Fix location of SyntaxError for a try block with both except and except*.

  • gh-98686: Merge the adaptive opcode logic into each instruction’s unquickened variant, and merge the logic in EXTENDED_ARG_QUICK into EXTENDED_ARG. With these changes, the quickening that happens at code object creation is now only responsible for initializing warmup counters and inserting superinstructions.

  • gh-99103: Fix the error reporting positions of specialized traceback anchors when the source line contains Unicode characters.

  • gh-99139: Improve the error suggestion for NameError exceptions for instances. Now if a NameError is raised in a method and the instance has an attribute that’s exactly equal to the name in the exception, the suggestion will include self.<NAME> instead of the closest match in the method scope. Patch by Pablo Galindo

  • gh-98401: Octal escapes with value larger than 0o377 (ex: "\477"), deprecated in Python 3.11, now produce a SyntaxWarning, instead of DeprecationWarning. In a future Python version they will be eventually a SyntaxError. Patch by Victor Stinner.

  • gh-98401: A backslash-character pair that is not a valid escape sequence now generates a SyntaxWarning, instead of DeprecationWarning. For example, re.compile("\d+\.\d+") now emits a SyntaxWarning ("\d" is an invalid escape sequence), use raw strings for regular expression: re.compile(r"\d+\.\d+"). In a future Python version, SyntaxError will eventually be raised, instead of SyntaxWarning. Patch by Victor Stinner.

  • gh-96793: Handle StopIteration and StopAsyncIteration raised in generator or coroutines in the bytecode, rather than in wrapping C code.

  • gh-98931: Improve the SyntaxError error message when the user types import x from y instead of from y import x. Patch by Pablo Galindo

  • gh-98852: Fix subscription of type aliases containing bare generic types or types like TypeVar: for example tuple[A, T][int] and tuple[TypeVar, T][int], where A is a generic type, and T is a type variable.

  • gh-98925: Lower the recursion depth for marshal on WASI to support (in-development) wasmtime 2.0.

  • gh-98783: Fix multiple crashes in debug mode when str subclasses are used instead of str itself.

  • gh-98811: Use complete source locations to simplify detection of __future__ imports which are not at the beginning of the file. Also corrects the offset in the exception raised in one case, which was off by one and impeded highlighting.

  • gh-96793: Add specialization of FOR_ITER for generators. Saves multiple layers of dispatch and checking to get from the FOR_ITER instruction in the caller to the RESUME in the generator.

  • gh-98762: Fix source locations of match sub-patterns.

  • gh-98586: Added the methods PyObject_Vectorcall() and PyObject_VectorcallMethod() to the Limited API along with the auxiliary macro constant PY_VECTORCALL_ARGUMENTS_OFFSET.

    The availability of these functions enables more efficient PEP 590 vector calls from binary extension modules that avoid argument boxing/unboxing overheads.

  • gh-99257: Fix an issue where member descriptors (such as those for __slots__) could behave incorrectly or crash instead of raising a TypeError when accessed via an instance of an invalid type.

  • gh-93143: Rather than changing co_code, the interpreter will now display a RuntimeWarning and assign None to any fast locals that are left unbound after jumps or del statements executed while tracing.

  • gh-96421: When calling into Python code from C code, through PyEval_EvalFrameEx() or a related C-API function, a shim frame in inserted into the call stack. This occurs in the _PyEval_EvalFrameDefault() function. The extra frame should be invisible to all Python and most C extensions, but out-of-process profilers and debuggers need to be aware of it. These shim frames can be detected by checking frame->owner == FRAME_OWNED_BY_CSTACK.

    Extensions implementing their own interpreters using PEP 523 need to be aware of this shim frame and the changes to the semantics of RETURN_VALUE, YIELD_VALUE, and RETURN_GENERATOR, which now clear the frame.

Construção

  • gh-98415: Fix detection of MAC addresses for uuid on certain OSs. Patch by Chaim Sanders

Núcleo e embutidos

  • gh-98686: Quicken all code objects, and specialize adaptive bytecode instructions more aggressively.

  • gh-92119: Print exception class name instead of its string representation when raising errors from ctypes calls.

  • gh-91058: ImportError raised from failed from <module> import <name> now include suggestions for the value of <name> based on the available names in <module>. Patch by Pablo Galindo

  • gh-96793: The FOR_ITER now leaves the iterator on the stack on termination of the loop. This is to assist specialization of loops for generators.

  • gh-90716: Add _pylong.py module. It includes asymptotically faster algorithms that can be used for operations on integers with many digits. It is used by longobject.c to speed up some operations.

  • gh-95389: Expose ETH_P_ALL and some of the ETHERTYPE_* constants in socket. Patch by Noam Cohen.

Biblioteca

  • gh-93696: Allow pdb to locate source for frozen modules in the standard library.

  • gh-99418: Fix bug in urllib.parse.urlparse() that causes URL schemes that begin with a digit, a plus sign, or a minus sign to be parsed incorrectly.

  • gh-94597: Deprecate asyncio.AbstractChildWatcher to be removed in Python 3.14. Patch by Kumar Aditya.

  • gh-99305: Improve performance of secrets.token_hex().

  • gh-74044: Fixed bug where inspect.signature() reported incorrect arguments for decorated methods.

  • gh-99275: Fix SystemError in ctypes when exception was not set during __initsubclass__.

  • gh-99277: Remove older version of _SSLProtocolTransport.get_write_buffer_limits in asyncio.sslproto

  • gh-99248: fix negative numbers failing in verify()

  • gh-99155: Fix statistics.NormalDist pickle with 0 and 1 protocols.

  • gh-93464: enum.auto() is now correctly activated when combined with other assignment values. E.g. ONE = auto(), 'some text' will now evaluate as (1, 'some text').

  • gh-99134: Update the bundled copy of pip to version 22.3.1.

  • gh-92584: Remove the distutils package. It was deprecated in Python 3.10 by PEP 632 “Deprecate distutils module”. For projects still using distutils and cannot be updated to something else, the setuptools project can be installed: it still provides distutils. Patch by Victor Stinner.

  • gh-98999: Now _pyio is consistent with _io in raising ValueError when executing methods over closed buffers.

  • gh-83004: Clean up refleak on failed module initialisation in _zoneinfo

  • gh-83004: Clean up refleaks on failed module initialisation in _pickle

  • gh-83004: Clean up refleak on failed module initialisation in _io.

  • gh-98897: Fix memory leak in math.dist() when both points don’t have the same dimension. Patch by Kumar Aditya.

  • gh-98878: Use the frame bound builtins when offering a name suggestion in traceback to prevent crashing when __builtins__ is not a dict.

  • gh-98139: In importlib._bootstrap, enhance namespace package repr to <module 'x' (namespace) from ['path']>.

  • gh-90352: Fix _SelectorDatagramTransport to inherit from DatagramTransport in asyncio. Patch by Kumar Aditya.

  • gh-98793: Fix argument typechecks in _overlapped.WSAConnect() and _overlapped.Overlapped.WSASendTo() functions.

  • gh-98744: Prevent crashing in traceback when retrieving the byte-offset for some source files that contain certain unicode characters.

  • gh-98740: Fix internal error in the re module which in very rare circumstances prevented compilation of a regular expression containing a conditional expression without the “else” branch.

  • gh-98703: Fix asyncio.StreamWriter.drain() to call protocol.connection_lost callback only once on Windows.

  • gh-98624: Add a mutex to unittest.mock.NonCallableMock to protect concurrent access to mock attributes.

  • gh-98658: The array.array class now supports subscripting, making it a generic type.

  • gh-98284: Improved TypeError message for undefined abstract methods of a abc.ABC instance. The names of the missing methods are surrounded by single-quotes to highlight them.

  • gh-96151: Allow BUILTINS to be a valid field name for frozen dataclasses.

  • gh-98086: Make sure patch.dict() can be applied on async functions.

  • gh-72719: Remove modules asyncore and asynchat, which were deprecated by PEP 594.

  • gh-96192: Fix handling of bytes path-like objects in os.ismount().

  • gh-94172: ftplib: Remove the FTP_TLS.ssl_version class attribute: use the context parameter instead. Patch by Victor Stinner

  • gh-94172: Remove the keyfile and certfile parameters from the ftplib, imaplib, poplib and smtplib modules, and the key_file, cert_file and check_hostname parameters from the http.client module, all deprecated since Python 3.6. Use the context parameter (ssl_context in imaplib) instead. Patch by Victor Stinner.

  • gh-83638: Add the autocommit attribute to sqlite3.Connection and the autocommit parameter to sqlite3.connect() to control PEP 249-compliant transaction handling. Patch by Erlend E. Aasland.

  • gh-92452: Fixed a race condition that could cause sysconfig.get_config_var() to incorrectly return None in multi-threaded programs.

  • gh-91803: Fix an error when using a method of objects mocked with unittest.mock.create_autospec() after it was sealed with unittest.mock.seal() function.

  • bpo-38523: shutil.copytree() now applies the ignore_dangling_symlinks argument recursively.

  • bpo-40358: Add walk_up argument in pathlib.PurePath.relative_to().

  • bpo-36267: Fix IndexError in argparse.ArgumentParser when a store_true action is given an explicit argument.

Documentação

  • gh-98832: Changes wording of docstring for pathlib.Path.iterdir().

  • gh-97966: Update uname docs to clarify the special nature of the platform attribute and to indicate when it became late-bound.

Testes

  • gh-98903: The Python test suite now fails with exit code 4 if no tests ran. It should help detecting typos in test names and test methods.

  • gh-98713: Fix a bug in the typing tests where a test relying on CPython-specific implementation details was not decorated with @cpython_only and was not skipped on other implementations.

  • gh-87390: Add tests for star-unpacking with PEP 646, and some other miscellaneous PEP 646 tests.

  • gh-96853: Added explicit coverage of Py_Initialize (and hence Py_InitializeEx) back to the embedding tests (all other embedding tests migrated to Py_InitializeFromConfig in Python 3.11)

  • bpo-34272: Some C API tests were moved into the new Lib/test/test_capi/ directory.

Construção

  • gh-99086: Fix -Wimplicit-int compiler warning in configure check for PTHREAD_SCOPE_SYSTEM.

  • gh-99016: Fix build with PYTHON_FOR_REGEN=python3.8.

  • gh-97731: Specify the full path to the source location for make docclean (needed for cross-builds).

  • gh-98949: Drop unused build dependency on readelf.

  • gh-98989: Use python3.11, if available, for regeneration and freezing.

  • gh-98831: Add new tooling, in Tools/cases_generator, to generate the interpreter switch statement from a list of opcode definitions. This only affects adding, modifying or removing instruction definitions. The instruction definitions now live in Python/bytecodes.c, in the form of a custom DSL (under development). The tooling reads this file and writes Python/generated_cases.c.h, which is then included by Python/ceval.c to provide most of the cases of the main interpreter switch.

  • gh-98817: Remove PCbuild/lib.pyproj: it’s not used for anything, is only a minor convenience for Visual Studio users (who probably mostly don’t even know about it), and it takes a lot of maintenance effort to keep updated.

  • gh-98776: Fix make regen-test-levenshtein for out-of-tree builds.

  • gh-98707: Don’t use vendored libmpdec headers if --with-system-libmpdec is passed to configure. Don’t use vendored libexpat headers if --with-system-expat is passed to configure.

Windows

  • gh-98689: Update Windows builds to zlib v1.2.13. v1.2.12 has CVE 2022-37434, but the vulnerable inflateGetHeader API is not used by Python.

  • gh-98790: Assumes that a missing DLLs directory means that standard extension modules are in the executable’s directory.

  • gh-98745: Update py.exe launcher to install 3.11 by default and 3.12 on request.

  • gh-98692: Fix the Gerenciador de instalação do Python ignoring unrecognized shebang lines instead of treating them as local paths

  • gh-94328: Update Windows installer to use SQLite 3.39.4.

macOS

  • gh-94328: Update macOS installer to SQLite 3.39.4.

API C

  • gh-98724: The Py_CLEAR, Py_SETREF and Py_XSETREF macros now only evaluate their argument once. If the argument has side effects, these side effects are no longer duplicated. Patch by Victor Stinner.

  • gh-98978: Fix use-after-free in Py_SetPythonHome(NULL), Py_SetProgramName(NULL) and _Py_SetProgramFullPath(NULL) function calls. Issue reported by Benedikt Reinartz. Patch by Victor Stinner.

  • gh-98410: Add getbufferproc and releasebufferproc to the stable API.

  • gh-98610: Some configurable capabilities of sub-interpreters have changed. They always allow subprocesses (subprocess) now, whereas before subprocesses could be optionally disallowed for a sub-interpreter. Instead os.exec() can now be disallowed. Disallowing daemon threads is now supported. Disallowing all threads is still allowed, but is never done by default. Note that the optional restrictions are only available through _Py_NewInterpreterFromConfig(), which isn’t a public API. They do not affect the main interpreter, nor Py_NewInterpreter().

  • gh-98608: A _PyInterpreterConfig has been added and _Py_NewInterpreter() has been renamed to _Py_NewInterpreterFromConfig(). The “isolated_subinterpreters” argument is now a granular config that captures the previous behavior. Note that this is all “private” API.

  • gh-96853: Py_InitializeEx now correctly calls PyConfig_Clear after initializing the interpreter (the omission didn’t cause a memory leak only because none of the dynamically allocated config fields are populated by the wrapper function)

  • gh-91248: Add PyFrame_GetVar() and PyFrame_GetVarString() functions to get a frame variable by its name. Patch by Victor Stinner.

Python 3.12.0 alpha 1

Data de lançamento: 2022-10-25

Segurança

  • gh-97616: Fix multiplying a list by an integer (list *= int): detect the integer overflow when the new allocated length is close to the maximum size. Issue reported by Jordan Limor. Patch by Victor Stinner.

  • gh-97514: On Linux the multiprocessing module returns to using filesystem backed unix domain sockets for communication with the forkserver process instead of the Linux abstract socket namespace. Only code that chooses to use the “forkserver” start method is affected.

    Abstract sockets have no permissions and could allow any user on the system in the same network namespace (often the whole system) to inject code into the multiprocessing forkserver process. This was a potential privilege escalation. Filesystem based socket permissions restrict this to the forkserver process user as was the default in Python 3.8 and earlier.

    This prevents Linux CVE 2022-42919.

  • gh-87389: http.server: Fix an open redirection vulnerability in the HTTP server when an URI path starts with //. Vulnerability discovered, and initial fix proposed, by Hamza Avvan.

  • gh-79096: LWPCookieJar and MozillaCookieJar create files with file mode 600 instead of 644 (Microsoft Windows is not affected)

  • gh-92888: Fix memoryview use after free when accessing the backing buffer in certain cases.

  • gh-68966: The deprecated mailcap module now refuses to inject unsafe text (filenames, MIME types, parameters) into shell commands. Instead of using such text, it will warn and act as if a match was not found (or for test commands, as if the test failed).

Núcleo e embutidos

  • gh-98374: Suppress ImportError for invalid query for help() command. Patch by Donghee Na.

  • gh-98461: Fix source location in bytecode for list, set and dict comprehensions as well as generator expressions.

  • gh-98354: Added unicode check for name attribute of spec argument passed in _imp.create_builtin() function.

  • gh-98398: Fix source location of ‘assert’ bytecodes.

  • gh-98390: Fix location of sub-expressions of boolean expressions, by reducing their scope to that of the sub-expression.

  • gh-98254: Modules from the standard library are now potentially suggested as part of the error messages displayed by the interpreter when an NameError is raised to the top level. Patch by Pablo Galindo

  • gh-97997: Add running column offset to the tokenizer state to avoid calculating AST column information with pointer arithmetic.

  • gh-97973: Modify the tokenizer to return all necessary information the parser needs to set location information in the AST nodes, so that the parser does not have to calculate those doing pointer arithmetic.

Biblioteca

Núcleo e embutidos

  • gh-97912: The compiler now avoids quadratic behavior when finding which instructions should use the LOAD_FAST_CHECK opcode.

  • gh-97002: Fix an issue where several frame objects could be backed by the same interpreter frame, possibly leading to corrupted memory and hard crashes of the interpreter.

  • gh-97943: Bugfix: PyFunction_GetAnnotations() should return a borrowed reference. It was returning a new reference.

  • gh-97922: The Garbage Collector now runs only on the eval breaker mechanism of the Python bytecode evaluation loop instead on object allocations. The GC can also run when PyErr_CheckSignals() is called so C extensions that need to run for a long time without executing any Python code also have a chance to execute the GC periodically.

  • gh-65961: When __package__ is different than __spec__.parent, raise a DeprecationWarning instead of ImportWarning.

    Also remove importlib.util.set_package() which was scheduled for removal.

  • gh-97850: Long deprecated, module_repr() should now be completely eradicated.

  • gh-86298: In cases where warnings.warn_explicit() consults the module’s loader, an DeprecationWarning is issued when m.__loader__ differs from m.__spec__.loader.

  • gh-97779: Ensure that all Python frame objects are backed by “complete” frames.

  • gh-91052: Add API for subscribing to modification events on selected dictionaries.

  • gh-97752: Fix possible data corruption or crashes when accessing the f_back member of newly-created generator or coroutine frames.

  • gh-97591: Fixed a missing incref/decref pair in Exception.__setstate__(). Patch by Ofey Chan.

  • gh-97670: Remove the sys.getdxp() function and the Tools/scripts/analyze_dxp.py script. DXP stands for “dynamic execution pairs”. They were related to DYNAMIC_EXECUTION_PROFILE and DXPAIRS macros which have been removed in Python 3.11. Python can now be built with ./configure --enable-pystats to gather statistics on Python opcodes. Patch by Victor Stinner.

  • gh-94526: Fix the Python path configuration used to initialized sys.path at Python startup. Paths are no longer encoded to UTF-8/strict to avoid encoding errors if it contains surrogate characters (bytes paths are decoded with the surrogateescape error handler). Patch by Victor Stinner.

  • gh-96670: The parser now raises SyntaxError when parsing source code containing null bytes. Patch by Pablo Galindo

  • gh-96975: Fix a crash occurring when PyEval_GetFrame() is called while the topmost Python frame is in a partially-initialized state.

  • gh-96848: Fix command line parsing: reject -X int_max_str_digits option with no value (invalid) when the PYTHONINTMAXSTRDIGITS environment variable is set to a valid limit. Patch by Victor Stinner.

  • gh-95921: Fix overly-broad source position information for chained comparisons used as branching conditions.

Biblioteca

  • gh-96821: Fix undefined behaviour in audioop.c.

Núcleo e embutidos

  • gh-96821: Fix undefined behaviour in _testcapimodule.c.

  • gh-95778: When ValueError is raised if an integer is larger than the limit, mention the sys.set_int_max_str_digits() function in the error message. Patch by Victor Stinner.

  • gh-96387: At Python exit, sometimes a thread holding the GIL can wait forever for a thread (usually a daemon thread) which requested to drop the GIL, whereas the thread already exited. To fix the race condition, the thread which requested the GIL drop now resets its request before exiting. Issue discovered and analyzed by Mingliang ZHAO. Patch by Victor Stinner.

  • gh-96864: Fix a possible assertion failure, fatal error, or SystemError if a line tracing event raises an exception while opcode tracing is enabled.

  • gh-95778: The PyLong_FromString function was refactored to make it more maintainable and extensible.

  • gh-96678: Fix undefined behaviour in C code of null pointer arithmetic.

  • gh-96754: Make sure that all frame objects created are created from valid interpreter frames. Prevents the possibility of invalid frames in backtraces and signal handlers.

  • gh-90997: Improve the performance of reading and writing inline bytecode caches on some platforms.

  • gh-96751: Remove dead code from CALL_FUNCTION_EX opcode.

  • gh-90751: memoryview now supports half-floats. Patch by Donghee Na and Antoine Pitrou.

  • gh-96678: Fix case of undefined behavior in ceval.c

Biblioteca

  • gh-64373: Convert _functools to argument clinic.

  • gh-96641: Do not expose KeyWrapper in _functools.

Núcleo e embutidos

  • gh-96636: Ensure that tracing, sys.setrace(), is turned on immediately. In pre-release versions of 3.11, some tracing events might have been lost when turning on tracing in a __del__ method or interrupt.

  • gh-96572: Fix use after free in trace refs build mode. Patch by Kumar Aditya.

  • gh-96611: When loading a file with invalid UTF-8 inside a multi-line string, a correct SyntaxError is emitted.

  • gh-96612: Make sure that incomplete frames do not show up in tracemalloc traces.

  • gh-90230: Fix compiler warnings and test failures when building with --enable-pystats.

  • gh-96587: Correctly raise SyntaxError on exception groups (PEP 654) on python versions prior to 3.11

  • gh-96569: Remove two cases of undefined behavior, by adding NULL checks.

  • gh-96582: Fix possible NULL pointer dereference in _PyThread_CurrentFrames. Patch by Kumar Aditya.

  • gh-91079: Separate Python recursion checking from C recursion checking which reduces the chance of C stack overflow and allows the recursion limit to be increased safely.

  • gh-93911: Fix an issue that could prevent LOAD_ATTR from specializing properly when accessing properties.

  • gh-96348: Emit a DeprecationWarning when throw(), throw() or athrow() are called with more than one argument.

  • gh-95196: Disable incorrect pickling of the C implemented classmethod descriptors.

  • gh-96364: Fix text signatures of list.__getitem__ and dict.__getitem__.

  • gh-96352: Fix AttributeError missing name and obj attributes in object.__getattribute__(). Patch by Philip Georgi.

  • gh-93554: Change the jump opcodes so that all conditional jumps are forward jumps. Backward jumps are converted by the assembler into a conditional forward jump whose target is the fallthrough block (and with a reversed condition), followed by an unconditional backward jump. For example:

    POP_JUMP_IF_TRUE BACKWARD_TARGET becomes POP_JUMP_IF_FALSE NEXT_BLOCK; JUMP BACKWARD_TARGET.

    All the directed conditional jump opcodes were removed: POP_JUMP_FORWARD_IF_TRUE, POP_JUMP_BACKWARD_IF_TRUE, POP_JUMP_FORWARD_IF_FALSE, POP_JUMP_BACKWARD_IF_FALSE, POP_JUMP_FORWARD_IF_NONE, POP_JUMP_BACKWARD_IF_NONE, POP_JUMP_FORWARD_IF_NOT_NONE, POP_JUMP_BACKWARD_IF_NOT_NONE.

    The corresponding opcodes without direction are no longer pseudo-instructions, and they implement the forward conditional jumps.

  • gh-96268: Loading a file with invalid UTF-8 will now report the broken character at the correct location.

  • gh-96237: The internal field _PyInterpreterFrame.f_func is renamed to _PyInterpreterFrame.f_funcobj and may be any object. The f_globals and f_builtin fields may hold junk values.

    It is safest to treat the _PyInterpreterFrame struct as opaque.

  • gh-96187: Fixed a bug that caused _PyCode_GetExtra to return garbage for negative indexes. Patch by Pablo Galindo

  • gh-96143: Add a new -X perf Python command line option as well as sys.activate_stack_trampoline() and sys.deactivate_stack_trampoline() function in the sys module that allows to set/unset the interpreter in a way that the Linux perf profiler can detect Python calls. The new sys.is_stack_trampoline_active() function allows to query the state of the perf trampoline. Design by Pablo Galindo. Patch by Pablo Galindo and Christian Heimes with contributions from Gregory P. Smith [Google] and Mark Shannon.

  • gh-96071: Fix a deadlock in PyGILState_Ensure() when allocating new thread state. Patch by Kumar Aditya.

  • gh-96046: PyType_Ready() now initializes ht_cached_keys and performs additional checks to ensure that type objects are properly configured. This avoids crashes in 3rd party packages that don’t use regular API to create new types.

  • gh-96005: On WASI ENOTCAPABLE is now mapped to PermissionError. The errno modules exposes the new error number. getpath.py now ignores PermissionError when it cannot open landmark files pybuilddir.txt and pyenv.cfg.

  • gh-93678: Added test a harness for direct unit tests of the compiler’s optimization stage. The _testinternalcapi.optimize_cfg() function runs the optimiser on a sequence of instructions. The CfgOptimizationTestCase class in test.support has utilities for invoking the optimizer and checking the output.

  • gh-95245: Reduces the size of a “simple” Python object from 8 to 6 words by moving the weakreflist pointer into the pre-header directly before the object’s dict/values pointer.

  • gh-90997: Compile virtual try/except blocks to handle exceptions raised during close() or throw() calls through a suspended frame.

  • gh-95977: Optimized calling __get__() with vectorcall. Patch by Kumar Aditya.

  • gh-91210: Improve error message when a parameter without a default value follows one with a default value, and show the same message, even when the non-default/default sequence is preceded by positional-only parameters.

  • gh-95922: Fixed bug where the compiler’s eliminate_empty_basic_blocks function ignores the last block of the code unit.

  • gh-95818: Skip over incomplete frames in PyThreadState_GetFrame().

  • gh-95876: Fix format string in _PyPegen_raise_error_known_location that can lead to memory corruption on some 64bit systems. The function was building a tuple with i (int) instead of n (Py_ssize_t) for Py_ssize_t arguments.

  • gh-95605: Fix misleading contents of error message when converting an all-whitespace string to float.

  • gh-95150: Update code object hashing and equality to consider all debugging and exception handling tables. This fixes an issue where certain non-identical code objects could be “deduplicated” during compilation.

  • gh-91146: Reduce allocation size of list from str.split() and str.rsplit(). Patch by Donghee Na and Inada Naoki.

  • gh-87092: Create a ‘jump target label’ abstraction in the compiler so that the compiler’s codegen stage does not work directly with basic blocks. This prepares the code for changes to the underlying CFG generation mechanism.

  • gh-95355: _PyPegen_Parser_New now properly detects token memory allocation errors. Patch by Honglin Zhu.

  • gh-90081: Run Python code in tracer/profiler function at full speed. Fixes slowdown in earlier versions of 3.11.

  • gh-95324: Emit a warning in debug mode if an object does not call PyObject_GC_UnTrack() before deallocation. Patch by Pablo Galindo.

  • gh-95245: Merge managed dict and values pointer into a single tagged pointer to save one word in the pre-header.

  • gh-93678: Add cfg_builder struct and refactor the relevant code so that a cfg can be constructed without an instance of the compiler struct.

  • gh-95185: Prevented crashes in the AST constructor when compiling some absurdly long expressions like "+0"*1000000. RecursionError is now raised instead. Patch by Pablo Galindo

  • gh-93351: ast.AST node positions are now validated when provided to compile() and other related functions. If invalid positions are detected, a ValueError will be raised.

  • gh-94438: Fix an issue that caused extended opcode arguments and some conditional pops to be ignored when calculating valid jump targets for assignments to the f_lineno attribute of frame objects. In some cases, this could cause inconsistent internal state, resulting in a hard crash of the interpreter.

  • gh-95060: Undocumented PyCode_Addr2Location function now properly returns when addrq argument is less than zero.

  • gh-95113: Replace all EXTENDED_ARG_QUICK instructions with basic EXTENDED_ARG instructions in unquickened code. Consumers of non-adaptive bytecode should be able to handle extended arguments the same way they were handled in CPython 3.10 and older.

  • gh-91409: Fix incorrect source location info caused by certain optimizations in the bytecode compiler.

Biblioteca

Núcleo e embutidos

  • gh-94036: Fix incorrect source location info for some multi-line attribute accesses and method calls.

  • gh-94938: Fix error detection in some builtin functions when keyword argument name is an instance of a str subclass with overloaded __eq__ and __hash__. Previously it could cause SystemError or other undesired behavior.

Biblioteca

  • gh-94996: ast.parse() will no longer parse function definitions with positional-only params when passed feature_version less than (3, 8). Patch by Shantanu Jain.

Núcleo e embutidos

  • gh-94739: Allow jumping within, out of, and across exception handlers in the debugger.

Biblioteca

  • gh-94949: ast.parse() will no longer parse parenthesized context managers when passed feature_version less than (3, 9). Patch by Shantanu Jain.

  • gh-94947: ast.parse() will no longer parse assignment expressions when passed feature_version less than (3, 8). Patch by Shantanu Jain.

Núcleo e embutidos

  • gh-91256: Ensures the program name is known for help text during interpreter startup.

  • gh-94869: Fix the column offsets for some expressions in multi-line f-strings ast nodes. Patch by Pablo Galindo.

  • gh-94893: Fix an issue where frame object manipulations could corrupt inline bytecode caches.

  • gh-94822: Fix an issue where lookups of metaclass descriptors may be ignored when an identically-named attribute also exists on the class itself.

  • gh-91153: Fix an issue where a bytearray item assignment could crash if it’s resized by the new value’s __index__() method.

  • gh-90699: Fix reference counting bug in bool.__repr__(). Patch by Kumar Aditya.

  • gh-94694: Fix an issue that could cause code with multi-line method lookups to have misleading or incorrect column offset information. In some cases (when compiling a hand-built AST) this could have resulted in a hard crash of the interpreter.

  • gh-93252: Fix an issue that caused internal frames to outlive failed Python function calls, possibly resulting in memory leaks or hard interpreter crashes.

  • gh-94215: Fix an issue where exceptions raised by line-tracing events would cause frames to be left in an invalid state, possibly resulting in a hard crash of the interpreter.

  • gh-92228: Disable the compiler’s inline-small-exit-blocks optimization for exit blocks that are associated with source code lines. This fixes a bug where the debugger cannot tell where an exception handler ends and the following code block begins.

  • gh-94485: Line number of a module’s RESUME instruction is set to 0 as specified in PEP 626.

  • gh-94438: Account for instructions that can push NULL to the stack when setting line number in a frame. Prevents some (unlikely) crashes.

  • gh-91719: Reload opcode when raising unknown opcode error in the interpreter main loop, for C compilers to generate dispatching code independently.

  • gh-94329: Compile and run code with unpacking of extremely large sequences (1000s of elements). Such code failed to compile. It now compiles and runs correctly.

  • gh-94360: Fixed a tokenizer crash when reading encoded files with syntax errors from stdin with non utf-8 encoded text. Patch by Pablo Galindo

  • gh-88116: Fix an issue when reading line numbers from code objects if the encoded line numbers are close to INT_MIN. Patch by Pablo Galindo

  • gh-94262: Don’t create frame objects for incomplete frames. Prevents the creation of generators and closures from being observable to Python and C extensions, restoring the behavior of 3.10 and earlier.

  • gh-94192: Fix error for dictionary literals with invalid expression as value.

  • gh-87995: types.MappingProxyType instances are now hashable if the underlying mapping is hashable.

  • gh-93883: Revise the display strategy of traceback enhanced error locations. The indicators are only shown when the location doesn’t span the whole line.

  • gh-94163: Add BINARY_SLICE and STORE_SLICE instructions for more efficient handling and better specialization of slicing operations, where the slice is explicit in the source code.

  • gh-94021: Fix unreachable code warning in Python/specialize.c.

  • gh-93911: Specialize LOAD_ATTR for objects with custom __getattribute__.

  • gh-93955: Improve performance of attribute lookups on objects with custom __getattribute__ and __getattr__. Patch by Ken Jin.

  • gh-93911: Specialize LOAD_ATTR for property() attributes.

  • gh-93678: Refactor compiler optimisation code so that it no longer needs the struct assembler and struct compiler passed around. Instead, each function takes the CFG and other data that it actually needs. This will make it possible to test this code directly.

  • gh-93841: When built with -enable-pystats, sys._stats_on(), sys._stats_off(), sys._stats_clear() and sys._stats_dump() functions have been added to enable gathering stats for parts of programs.

  • gh-93516: Store offset of first traceable instruction in code object to avoid having to recompute it for each instruction when tracing.

  • gh-93516: Lazily create a table mapping bytecode offsets to line numbers to speed up calculation of line numbers when tracing.

  • gh-89828: types.GenericAlias no longer relays the __class__ attribute. For example, isinstance(list[int], type) no longer returns True.

  • gh-93678: Refactor the compiler to reduce boilerplate and repetition.

  • gh-93671: Fix some exponential backtrace case happening with deeply nested sequence patterns in match statements. Patch by Pablo Galindo

  • gh-93662: Make sure that the end column offsets are correct in multi-line method calls. Previously, the end column could precede the column offset.

Biblioteca

Núcleo e embutidos

  • gh-93621: Change order of bytecode instructions emitted for with and async with to reduce the number of entries in the exception table.

  • gh-93533: Reduce the size of the inline cache for LOAD_METHOD by 2 bytes.

  • gh-93444: Removed redundant fields from the compiler’s basicblock struct: b_nofallthrough, b_exit, b_return. They can be easily calculated from the opcode of the last instruction of the block.

  • gh-93429: LOAD_METHOD instruction has been removed. It was merged back into LOAD_ATTR.

  • gh-93418: Fixed an assert where an f-string has an equal sign ‘=’ following an expression, but there’s no trailing brace. For example, f”{i=”.

  • gh-93382: Cache the result of PyCode_GetCode() function to restore the O(1) lookup of the co_code attribute.

  • gh-93359: Ensure that custom ast nodes without explicit end positions can be compiled. Patch by Pablo Galindo.

  • gh-93356: Code for exception handlers is emitted at the end of the code unit’s bytecode. This avoids one jump when no exception is raised.

  • gh-93354: Use exponential backoff for specialization counters in the interpreter. Can reduce the number of failed specializations significantly and avoid slowdown for those parts of a program that are not suitable for specialization.

  • gh-93283: Improve error message for invalid syntax of conversion character in f-string expressions.

  • gh-93345: Fix a crash in substitution of a TypeVar in nested generic alias after TypeVarTuple.

  • gh-93223: When a bytecode instruction jumps to an unconditional jump instruction, the first instruction can often be optimized to target the unconditional jump’s target directly. For tracing reasons, this would previously only occur if both instructions have the same line number. This also now occurs if the unconditional jump is artificial, i.e., if it has no associated line number.

  • gh-84694: The --experimental-isolated-subinterpreters configure option and EXPERIMENTAL_ISOLATED_SUBINTERPRETERS macro have been removed.

  • gh-91924: Fix __lltrace__ debug feature if the stdout encoding is not UTF-8. Patch by Victor Stinner.

  • gh-93040: Wraps unused parameters in Objects/obmalloc.c with Py_UNUSED.

  • gh-93143: Avoid NULL checks for uninitialized local variables by determining at compile time which variables must be initialized.

  • gh-93061: Backward jumps after async for loops are no longer given dubious line numbers.

  • gh-93065: Fix contextvars HAMT implementation to handle iteration over deep trees.

    The bug was discovered and fixed by Eli Libman. See MagicStack/immutables#84 for more details.

  • gh-93012: Added the new function PyType_FromMetaclass(), which generalizes the existing PyType_FromModuleAndSpec() using an additional metaclass argument. This is useful for language binding tools, where it can be used to intercept type-related operations like subclassing or static attribute access by specifying a metaclass with custom slots.

    Importantly, PyType_FromMetaclass() is available in the Limited API, which provides a path towards migrating more binding tools onto the Stable ABI.

  • gh-93021: Fix the __text_signature__ for __get__() methods implemented in C. Patch by Jelle Zijlstra.

  • gh-89914: The operand of the YIELD_VALUE instruction is set to the stack depth. This is done to help frame handling on yield and may assist debuggers.

  • gh-92955: Fix memory leak in code object’s lines and positions iterators as they were not finalized at exit. Patch by Kumar Aditya.

  • gh-92930: Fixed a crash in _pickle.c from mutating collections during __reduce__ or persistent_id.

  • gh-90690: The PRECALL instruction has been removed. It offered only a small advantage for specialization and is not needed in the vast majority of cases.

  • gh-92914: Always round the allocated size for lists up to the nearest even number.

  • gh-92858: Improve error message for some suites with syntax error before ‘:’

  • gh-90473: Decrease default recursion limit on WASI to address limited call stack size.

  • gh-92804: Fix memory leak in memoryview iterator as it was not finalized at exit. Patch by Kumar Aditya.

  • gh-92777: Specialize LOAD_METHOD for objects with lazy dictionaries. Patch by Ken Jin.

  • gh-92658: Add support for connecting and binding to Hyper-V sockets on Windows Hyper-V hosts and guests.

  • gh-92236: Remove spurious “LINE” event when starting a generator or coroutine, visible tracing functions implemented in C.

Biblioteca

  • gh-91102: _warnings.warn_explicit() is ported to Argument Clinic.

Núcleo e embutidos

  • gh-92619: Make the compiler duplicate an exit block only if none of its instructions have a lineno (previously only the first instruction in the block was checked, leading to unnecessarily duplicated blocks).

  • gh-88750: The deprecated debug build only PYTHONTHREADDEBUG environment variable no longer does anything.

Biblioteca

  • gh-92261: Fix hang when trying to iterate over a typing.Union.

Núcleo e embutidos

  • gh-91432: Specialized the FOR_ITER opcode using the PEP 659 machinery

  • gh-91399: Removed duplicate ‘{0, 0, 0, 0, 0, 0}’ entry in ‘Objects/unicodetype_db.h’.

  • gh-91578: Updates the error message for abstract class.

  • bpo-47091: Improve performance of repetition of list and tuple by using memcpy to copy data and performing the reference increments in one step.

  • bpo-46142: Make --help output shorter by moving some info to the new --help-env and --help-xoptions command-line options. Also add --help-all option to print complete usage.

  • bpo-42316: Document some places where an assignment expression needs parentheses.

Biblioteca

  • gh-89237: Fix hang on Windows in subprocess.wait_closed() in asyncio with ProactorEventLoop. Patch by Kumar Aditya.

  • gh-97928: tkinter.Text.count() raises now an exception for options starting with “-” instead of silently ignoring them.

  • gh-98393: The os module no longer accepts bytes-like paths, like bytearray and memoryview types: only the exact bytes type is accepted for bytes strings. Patch by Victor Stinner.

  • gh-98363: Added itertools.batched() to batch data into lists of a given length with the last list possibly being shorter than the others.

  • gh-98331: Update the bundled copies of pip and setuptools to versions 22.3 and 65.5.0 respectively.

  • gh-98307: A createSocket() method was added to SysLogHandler.

  • gh-96035: Fix bug in urllib.parse.urlparse() that causes certain port numbers containing whitespace, underscores, plus and minus signs, or non-ASCII digits to be incorrectly accepted.

  • gh-98257: Make sys.setprofile() and sys.settrace() functions reentrant. They can no long fail with: RuntimeError("Cannot install a trace function while another trace function is being installed"). Patch by Victor Stinner.

  • gh-98251: Allow venv to pass along PYTHON* variables to ensurepip and pip when they do not impact path resolution

  • gh-94597: Deprecated asyncio.AbstractEventLoopPolicy.get_child_watcher() and asyncio.AbstractEventLoopPolicy.set_child_watcher() methods to be removed in Python 3.14. Patch by Kumar Aditya.

  • gh-98178: On macOS, fix a crash in syslog.syslog() in multi-threaded applications. On macOS, the libc syslog() function is not thread-safe, so syslog.syslog() no longer releases the GIL to call it. Patch by Victor Stinner.

  • gh-44098: Release the GIL when creating mmap.mmap objects on Unix.

  • gh-87730: Wrap network errors consistently in urllib FTP support, so the test suite doesn’t fail when a network is available but the public internet is not reachable.

  • gh-94597: The child watcher classes MultiLoopChildWatcher, FastChildWatcher and SafeChildWatcher are deprecated and will be removed in Python 3.14. Patch by Kumar Aditya.

  • gh-98023: Change default child watcher to PidfdChildWatcher on Linux systems which supports it. Patch by Kumar Aditya.

  • gh-90985: Earlier in 3.11 we deprecated asyncio.Task.cancel("message"). We realized we were too harsh, and have undeprecated it.

  • gh-65961: Do not rely solely on __cached__ on modules; code will also support __spec__.cached.

  • gh-97646: Replace deprecated application/javascript with text/javascript in mimetypes. See RFC 9239. Patch by Noam Cohen.

  • gh-97930: Apply changes from importlib_resources 5.8 and 5.9: Traversable.joinpath provides a concrete implementation. as_file now supports directories of resources.

  • gh-97850: Remove deprecated importlib.util.set_loader() and importlib.util.module_for_loader() from importlib.util.

  • gh-97837: Change deprecate warning message in unittest from

    It is deprecated to return a value!=None

    to

    It is deprecated to return a value that is not None from a test case

  • gh-97825: Fixes AttributeError when subprocess.check_output() is used with argument input=None and either of the arguments encoding or errors are used.

  • gh-97008: NameError and AttributeError spelling suggestions provided since gh-82711 are now also emitted by the pure Python traceback module. Tests for those suggestions now exercise both implementations to ensure they are equivalent. Patch by Carl Friedrich Bolz-Tereick and Łukasz Langa.

  • gh-97799: dataclass now uses inspect.get_annotations() to examine the annotations on class objects.

  • gh-97781: Removed deprecated interfaces in importlib.metadata (entry points accessed as dictionary, implicit dictionary construction of sequence of EntryPoint objects, mutablility of EntryPoints result, access of entry point by index). entry_points now has a simpler, more straightforward API (returning EntryPoints).

  • gh-96827: Avoid spurious tracebacks from asyncio when default executor cleanup is delayed until after the event loop is closed (e.g. as the result of a keyboard interrupt).

  • gh-95534: gzip.GzipFile.read() reads 10% faster.

  • gh-97592: Avoid a crash in the C version of asyncio.Future.remove_done_callback() when an evil argument is passed.

  • gh-97639: Remove tokenize.NL check from tabnanny.

  • gh-97545: Make Semaphore run faster.

  • gh-73588: Fix generation of the default name of tkinter.Checkbutton. Previously, checkbuttons in different parent widgets could have the same short name and share the same state if arguments “name” and “variable” are not specified. Now they are globally unique.

  • gh-96865: fix Flag to use boundary CONFORM

    This restores previous Flag behavior of allowing flags with non-sequential values to be combined; e.g.

    class Skip(Flag): TWO = 2 EIGHT = 8

    Skip.TWO | Skip.EIGHT -> <Skip.TWO|EIGHT: 10>

  • gh-97005: Update bundled libexpat to 2.4.9

  • gh-85760: Fix race condition in asyncio where process_exited() called before the pipe_data_received() leading to inconsistent output. Patch by Kumar Aditya.

  • gh-96704: Pass the correct contextvars.Context when a asyncio exception handler is called on behalf of a task or callback handle. This adds a new Task method, get_context, and also a new Handle method with the same name. If this method is not found on a task object (perhaps because it is a third-party library that does not yet provide this method), the context prevailing at the time the exception handler is called is used.

  • gh-96819: Fixed check in multiprocessing.resource_tracker that guarantees that the length of a write to a pipe is not greater than PIPE_BUF.

  • gh-95865: Reduce urllib.parse.quote_from_bytes() memory use on large values.

    Contribuição de Dennis Sweeney.

  • gh-96741: Corrected type annotation for dataclass attribute pstats.FunctionProfile.ncalls to be str.

  • gh-96734: Update unicodedata database to Unicode 15.0.0.

  • gh-96735: Fix undefined behaviour in struct.unpack().

  • gh-46412: Improve performance of bool(db) for large ndb/gdb databases. Previously this would call len(db) which would iterate over all keys – the answer (empty or not) is known after the first key.

  • gh-96652: Fix the faulthandler implementation of faulthandler.register(signal, chain=True) if the sigaction() function is not available: don’t call the previous signal handler if it’s NULL. Patch by Victor Stinner.

  • gh-68163: Correct conversion of numbers.Rational’s to float.

  • gh-96538: Speed up bisect.bisect() functions by taking advantage of type-stability.

  • gh-96465: Fraction hashes are now cached.

  • gh-96079: In typing, fix missing field name and incorrect __module__ in _AnnotatedAlias.

  • gh-96415: Remove types._cell_factory from module namespace.

  • gh-95987: Fix repr of Any subclasses.

  • gh-96388: Work around missing socket functions in socket’s __repr__.

  • gh-96385: Fix TypeVarTuple.__typing_prepare_subst__. TypeError was not raised when using more than one TypeVarTuple, like [*T, *V] in type alias substitutions.

  • gh-96142: Add match_args, kw_only, slots, and weakref_slot to _DataclassParams.

  • gh-96073: In inspect, fix overeager replacement of “typing.” in formatting annotations.

  • gh-89258: Added a getChildren() method to logging.Logger, to get the immediate child loggers of a logger.

  • gh-96346: Use double caching for compiled RE patterns.

  • gh-96349: Fixed a minor performance regression in threading.Event.__init__()

  • gh-90467: Fix asyncio.streams.StreamReaderProtocol to keep a strong reference to the created task, so that it’s not garbage collected

  • gh-96172: Fix a bug in unicodedata: east_asian_width used to return the wrong value for unassigned characters; and for yet unassigned, but reserved characters.

  • gh-96159: Fix a performance regression in logging TimedRotatingFileHandler. Only check for special files when the rollover time has passed.

  • gh-96175: Fix unused localName parameter in the Attr class in xml.dom.minidom.

  • gh-96145: Add AttrDict to JSON module for use with object_hook.

  • gh-96052: Fix handling compiler warnings (SyntaxWarning and DeprecationWarning) in codeop.compile_command() when checking for incomplete input. Previously it emitted warnings and raised a SyntaxError. Now it always returns None for incomplete input without emitting any warnings.

  • gh-96125: Fix incorrect condition that causes sys.thread_info.name to be wrong on pthread platforms.

  • gh-96019: Fix a bug in the makeunicodedata.py script leading to about 13 KiB of space saving in the unicodedata module, specifically the character decomposition data.

  • gh-95463: Remove an incompatible change from bpo-28080 that caused a regression that ignored the utf8 in ZipInfo.flag_bits. Patch by Pablo Galindo.

  • gh-69142: Add %:z strftime format code (generates tzoffset with colons as separator), see strftime() and strptime() behavior.

  • gh-95899: Fix asyncio.Runner to call asyncio.set_event_loop() only once to avoid calling attach_loop() multiple times on child watchers. Patch by Kumar Aditya.

  • gh-95736: Fix unittest.IsolatedAsyncioTestCase to set event loop before calling setup functions. Patch by Kumar Aditya.

  • gh-95865: Speed up urllib.parse.quote_from_bytes() by replacing a list comprehension with map().

  • gh-95861: Add support for computing Spearman’s correlation coefficient to the existing statistics.correlation() function.

  • gh-95804: Fix logging shutdown handler so it respects MemoryHandler.flushOnClose.

  • gh-95704: When a task catches asyncio.CancelledError and raises some other error, the other error should generally not silently be suppressed.

  • gh-95149: The HTTPStatus enum offers a couple of properties to indicate the HTTP status category e.g. HTTPStatus.OK.is_success.

  • gh-95609: Update bundled pip to 22.2.2.

  • gh-95289: Fix asyncio.TaskGroup to propagate exception when asyncio.CancelledError was replaced with another exception by a context manager. Patch by Kumar Aditya and Guido van Rossum.

  • gh-94909: Fix incorrect joining of relative Windows paths with drives in pathlib.PurePath initializer.

  • gh-95385: Faster json.dumps() when sorting of keys is not requested (default).

  • gh-83901: Improve Signature.bind error message for missing keyword-only arguments.

  • gh-95339: Update bundled pip to 22.2.1.

  • gh-95045: Fix GC crash when deallocating _lsprof.Profiler by untracking it before calling any callbacks. Patch by Kumar Aditya.

  • gh-95231: Fail gracefully if EPERM or ENOSYS is raised when loading crypt methods. This may happen when trying to load MD5 on a Linux kernel with FIPS enabled.

  • gh-95097: Fix asyncio.run() for asyncio.Task implementations without uncancel() method. Patch by Kumar Aditya.

  • gh-95087: Fix IndexError in parsing invalid date in the email module.

  • gh-95199: Upgrade bundled setuptools to 63.2.0.

  • gh-95194: Upgrade bundled pip to 22.2.

  • gh-93899: Fix check for existence of os.EFD_CLOEXEC, os.EFD_NONBLOCK and os.EFD_SEMAPHORE flags on older kernel versions where these flags are not present. Patch by Kumar Aditya.

  • gh-95166: Fix concurrent.futures.Executor.map() to cancel the currently waiting on future on an error - e.g. TimeoutError or KeyboardInterrupt.

  • gh-95132: Fix a sqlite3 regression where *args and **kwds were incorrectly relayed from connect() to the Connection factory. The regression was introduced in 3.11a1 with PR 24421 (gh-85128). Patch by Erlend E. Aasland.

  • gh-93157: Fix fileinput module didn’t support errors option when inplace is true.

  • gh-91212: Fixed flickering of the turtle window when the tracer is turned off. Patch by Shin-myoung-serp.

  • gh-95077: Add deprecation warning for enum member.member access (e.g. Color.RED.BLUE). Remove EnumMeta.__getattr__.

  • gh-95109: Ensure that timeouts scheduled with asyncio.Timeout that have already expired are delivered promptly.

  • gh-95105: wsgiref.types.InputStream.__iter__() should return Iterator[bytes], not Iterable[bytes]. Patch by Shantanu Jain.

  • gh-95066: Replaced assert with exception in ast.parse(), when feature_version has an invalid major version. Patch by Shantanu Jain.

  • gh-77617: Add sqlite3 command-line interface. Patch by Erlend Aasland.

  • gh-95005: Replace _PyAccu with _PyUnicodeWriter in JSON encoder and StringIO and remove the _PyAccu implementation.

  • gh-90085: Remove -c/--clock and -t/--time CLI options of timeit. The options had been deprecated since Python 3.3 and the functionality was removed in Python 3.7. Patch by Shantanu Jain.

  • gh-94857: Fix refleak in _io.TextIOWrapper.reconfigure. Patch by Kumar Aditya.

  • gh-94821: Fix binding of unix socket to empty address on Linux to use an available address from the abstract namespace, instead of “0”.

  • gh-94736: Fix crash when deallocating an instance of a subclass of _multiprocessing.SemLock. Patch by Kumar Aditya.

  • gh-81620: Add random.binomialvariate().

  • gh-74116: Allow asyncio.StreamWriter.drain() to be awaited concurrently by multiple tasks. Patch by Kumar Aditya.

  • gh-87822: When called with capture_locals=True, the traceback module functions swallow exceptions raised from calls to repr() on local variables of frames. This is in order to prioritize the original exception over rendering errors. An indication of the failure is printed in place of the missing value. (Patch by Simon-Martin Schroeder).

  • gh-88050: Fix asyncio subprocess transport to kill process cleanly when process is blocked and avoid RuntimeError when loop is closed. Patch by Kumar Aditya.

  • gh-94637: SSLContext.set_default_verify_paths() now releases the GIL around SSL_CTX_set_default_verify_paths call. The function call performs I/O and CPU intensive work.

  • gh-94309: Deprecate aliases typing.Hashable and typing.Sized

  • gh-92546: An undocumented python -m pprint benchmark is moved into pprint suite of pyperformance. Patch by Oleg Iarygin.

  • gh-94607: Fix subclassing complex generics with type variables in typing. Previously an error message saying Some type variables ... are not listed in Generic[...] was shown. typing no longer populates __parameters__ with the __parameters__ of a Python class.

  • gh-94619: Remove the long-deprecated module_repr() from importlib.

  • gh-93910: The ability to access the other values of an enum on an enum (e.g. Color.RED.BLUE) has been restored in order to fix a performance regression.

  • gh-93896: Fix asyncio.run() and unittest.IsolatedAsyncioTestCase to always the set event loop as it was done in Python 3.10 and earlier. Patch by Kumar Aditya.

  • gh-94343: Allow setting the attributes of reprlib.Repr during object initialization

  • gh-94382: Port static types of _multiprocessing module to heap types. Patch by Kumar Aditya.

  • gh-78724: Fix crash in struct.Struct when it was not completely initialized by initializing it in __new__(). Patch by Kumar Aditya.

  • gh-94510: Re-entrant calls to sys.setprofile() and sys.settrace() now raise RuntimeError. Patch by Pablo Galindo.

  • gh-92336: Fix bug where linecache.getline() fails on bad files with UnicodeDecodeError or SyntaxError. It now returns an empty string as per the documentation.

  • gh-94398: Once a asyncio.TaskGroup has started shutting down (i.e., at least one task has failed and the task group has started cancelling the remaining tasks), it should not be possible to add new tasks to the task group.

  • gh-94383: xml.etree: Remove the ElementTree.Element.copy() method of the pure Python implementation, deprecated in Python 3.10, use the copy.copy() function instead. The C implementation of xml.etree has no copy() method, only a __copy__() method. Patch by Victor Stinner.

  • gh-94379: zipimport: Remove find_loader() and find_module() methods, deprecated in Python 3.10: use the find_spec() method instead. See PEP 451 for the rationale. Patch by Victor Stinner.

  • gh-94352: shlex.split(): Passing None for s argument now raises an exception, rather than reading sys.stdin. The feature was deprecated in Python 3.9. Patch by Victor Stinner.

  • gh-94318: Strip trailing spaces in pydoc text output.

  • gh-89988: Fix memory leak in pickle.Pickler when looking up dispatch_table. Patch by Kumar Aditya.

  • gh-90016: Deprecate sqlite3 default adapters and converters. Patch by Erlend E. Aasland.

  • gh-94254: Fixed types of struct module to be immutable. Patch by Kumar Aditya.

  • gh-93259: Now raise ValueError when None or an empty string are passed to Distribution.from_name (and other callers).

  • gh-74696: shutil.make_archive() now passes the root_dir argument to custom archivers which support it.

  • gh-94216: The dis module now has the opcodes for pseudo instructions (those which are used by the compiler during code generation but then removed or replaced by real opcodes before the final bytecode is emitted).

  • gh-93096: Removed undocumented python -m codecs. Use python -m unittest test.test_codecs.EncodedFileTest instead.

  • gh-94207: Made _struct.Struct GC-tracked in order to fix a reference leak in the _struct module.

  • gh-93096: Removed undocumented -t argument of python -m base64. Use python -m unittest test.test_base64.LegacyBase64TestCase.test_encodebytes instead.

  • gh-94226: Remove the locale.format() function, deprecated in Python 3.7: use locale.format_string() instead. Patch by Victor Stinner.

  • gh-94199: Remove the ssl.match_hostname() function. The ssl.match_hostname() was deprecated in Python 3.7. OpenSSL performs hostname matching since Python 3.7, Python no longer uses the ssl.match_hostname() function. Patch by Victor Stinner.

  • gh-94214: Document the context object used in the venv.EnvBuilder class, and add the new environment’s library path to it.

  • gh-94199: Remove the ssl.wrap_socket() function, deprecated in Python 3.7: instead, create a ssl.SSLContext object and call its ssl.SSLContext.wrap_socket method. Any package that still uses ssl.wrap_socket() is broken and insecure. The function neither sends a SNI TLS extension nor validates server hostname. Code is subject to CWE 295 Improper Certificate Validation. Patch by Victor Stinner.

  • gh-94199: Remove the ssl.RAND_pseudo_bytes() function, deprecated in Python 3.6: use os.urandom() or ssl.RAND_bytes() instead. Patch by Victor Stinner.

  • gh-94199: hashlib: Remove the pure Python implementation of hashlib.pbkdf2_hmac(), deprecated in Python 3.10. Python 3.10 and newer requires OpenSSL 1.1.1 (PEP 644): this OpenSSL version provides a C implementation of pbkdf2_hmac() which is faster. Patch by Victor Stinner.

  • gh-94196: gzip: Remove the filename attribute of gzip.GzipFile, deprecated since Python 2.6, use the name attribute instead. In write mode, the filename attribute added '.gz' file extension if it was not present. Patch by Victor Stinner.

  • gh-94182: run the asyncio.PidfdChildWatcher on the running loop, this allows event loops to run subprocesses when there is no default event loop running on the main thread

  • gh-94169: Remove io.OpenWrapper and _pyio.OpenWrapper, deprecated in Python 3.10: just use open() instead. The open() (io.open()) function is a built-in function. Since Python 3.10, _pyio.open() is also a static method. Patch by Victor Stinner.

  • gh-91742: Fix pdb crash after jump caused by a null pointer dereference. Patch by Kumar Aditya.

  • gh-94101: Manual instantiation of ssl.SSLSession objects is no longer allowed as it lead to misconfigured instances that crashed the interpreter when attributes where accessed on them.

  • gh-84753: inspect.iscoroutinefunction(), inspect.isgeneratorfunction(), and inspect.isasyncgenfunction() now properly return True for duck-typed function-like objects like instances of unittest.mock.AsyncMock.

    This makes inspect.iscoroutinefunction() consistent with the behavior of asyncio.iscoroutinefunction(). Patch by Mehdi ABAAKOUK.

  • gh-94028: Fix a regression in the sqlite3 where statement objects were not properly cleared and reset after use in cursor iters. The regression was introduced by PR 27884 in Python 3.11a1. Patch by Erlend E. Aasland.

  • gh-93973: Add keyword argument all_errors to asyncio.create_connection so that multiple connection errors can be raised as an ExceptionGroup.

  • gh-93963: Officially deprecate from importlib.abc classes moved to importlib.resources.abc.

  • gh-93858: Prevent error when activating venv in nested fish instances.

  • gh-93820: Pickle enum.Flag by name.

  • gh-93847: Fix repr of enum of generic aliases.

  • gh-91404: Revert the re memory leak when a match is terminated by a signal or memory allocation failure as the implemented fix caused a major performance regression.

  • gh-83499: Fix double closing of file description in tempfile.

  • gh-93820: Fixed a regression when copy.copy()-ing enum.Flag with multiple flag members.

  • gh-79512: Fixed names and __module__ value of weakref classes ReferenceType, ProxyType, CallableProxyType. It makes them pickleable.

  • gh-91389: Fix an issue where dis utilities could report missing or incorrect position information in the presence of CACHE entries.

  • gh-93626: Set __future__.annotations to have a None mandatoryRelease to indicate that it is currently ‘TBD’.

  • gh-90473: Emscripten and WASI have no home directory and cannot provide PEP 370 user site directory.

  • gh-90494: copy.copy() and copy.deepcopy() now always raise a TypeError if __reduce__() returns a tuple with length 6 instead of silently ignore the 6th item or produce incorrect result.

  • gh-90549: Fix a multiprocessing bug where a global named resource (such as a semaphore) could leak when a child process is spawned (as opposed to forked).

  • gh-93521: Fixed a case where dataclasses would try to add __weakref__ into the __slots__ for a dataclass that specified weakref_slot=True when it was already defined in one of its bases. This resulted in a TypeError upon the new class being created.

  • gh-79579: sqlite3 now correctly detects DML queries with leading comments. Patch by Erlend E. Aasland.

  • gh-93421: Update sqlite3.Cursor.rowcount when a DML statement has run to completion. This fixes the row count for SQL queries like UPDATE ... RETURNING. Patch by Erlend E. Aasland.

  • gh-93475: Expose FICLONE and FICLONERANGE constants in fcntl. Patch by Illia Volochii.

  • gh-93370: Deprecate version and version_info.

  • gh-91810: Suppress writing an XML declaration in open files in ElementTree.write() with encoding='unicode' and xml_declaration=None.

  • gh-91162: Support splitting of unpacked arbitrary-length tuple over TypeVar and TypeVarTuple parameters. For example:

    • A[T, *Ts][*tuple[int, ...]] -> A[int, *tuple[int, ...]]

    • A[*Ts, T][*tuple[int, ...]] -> A[*tuple[int, ...], int]

  • gh-93353: Fix the importlib.resources.as_file() context manager to remove the temporary file if destroyed late during Python finalization: keep a local reference to the os.remove() function. Patch by Victor Stinner.

  • gh-83658: Make multiprocessing.Pool raise an exception if maxtasksperchild is not None or a positive int.

  • gh-93312: Add os.PIDFD_NONBLOCK flag to open a file descriptor for a process with os.pidfd_open() in non-blocking mode. Patch by Kumar Aditya.

  • gh-88123: Implement Enum.__contains__ that returns True or False to replace the deprecated behaviour that would sometimes raise a TypeError.

  • gh-93297: Make asyncio task groups prevent child tasks from being GCed

  • gh-85308: Changed argparse.ArgumentParser to use filesystem encoding and error handler instead of default text encoding to read arguments from file (e.g. fromfile_prefix_chars option). This change affects Windows; argument file should be encoded with UTF-8 instead of ANSI Codepage.

  • gh-93156: Accessing the pathlib.PurePath.parents sequence of an absolute path using negative index values produced incorrect results.

  • gh-93162: Add the ability for logging.config.dictConfig() to usefully configure QueueHandler and QueueListener as a pair, and add logging.getHandlerByName() and logging.getHandlerNames() APIs to allow access to handlers by name.

  • gh-93243: The smtpd module was removed per the schedule in PEP 594.

  • gh-92886: Replace assert statements with raise AssertionError() in BaseHandler so that the tested behaviour is maintained running with optimizations (-O).

  • gh-90155: Fix broken asyncio.Semaphore when acquire is cancelled.

  • gh-90817: The locale.resetlocale() function is deprecated and will be removed in Python 3.13. Use locale.setlocale(locale.LC_ALL, "") instead. Patch by Victor Stinner.

  • gh-91513: Added taskName attribute to logging module for use with asyncio tasks.

  • gh-74696: shutil.make_archive() no longer temporarily changes the current working directory during creation of standard .zip or tar archives.

  • gh-92728: The re.template() function and the corresponding re.TEMPLATE and re.T flags are restored after they were removed in 3.11.0b1, but they are now deprecated, so they might be removed from Python 3.13.

  • gh-93033: Search in some strings (platform dependent i.e [U+0xFFFF, U+0x0100] on Windows or [U+0xFFFFFFFF, U+0x00010000] on Linux 64-bit) are now up to 10 times faster.

  • gh-89973: Fix re.error raised in fnmatch if the pattern contains a character range with upper bound lower than lower bound (e.g. [c-a]). Now such ranges are interpreted as empty ranges.

  • gh-93044: No longer convert the database argument of sqlite3.connect() to bytes before passing it to the factory.

  • gh-93010: In a very special case, the email package tried to append the nonexistent InvalidHeaderError to the defect list. It should have been InvalidHeaderDefect.

  • gh-92986: Fix ast.unparse() when ImportFrom.level is None

  • gh-92932: Now dis() and get_instructions() handle operand values for instructions prefixed by EXTENDED_ARG_QUICK. Patch by Sam Gross and Donghee Na.

  • gh-92675: Fix venv.ensure_directories() to accept pathlib.Path arguments in addition to str paths. Patch by David Foster.

  • gh-87901: Removed the encoding argument from os.popen() that was added in 3.11b1.

  • gh-91922: Fix function sqlite.connect() and the sqlite.Connection constructor on non-UTF-8 locales. Also, they now support bytes paths non-decodable with the current FS encoding.

  • gh-92869: Added c_time_t to ctypes, which has the same size as the time_t type in C.

  • gh-92839: Fixed crash resulting from calling bisect.insort() or bisect.insort_left() with the key argument not equal to None.

  • gh-90473: subprocess now fails early on Emscripten and WASI platforms to work around missing os.pipe() on WASI.

  • gh-89325: Removed many old deprecated unittest features: TestCase method aliases, undocumented and broken TestCase method assertDictContainsSubset, undocumented TestLoader.loadTestsFromModule parameter use_load_tests, and an underscored alias of the TextTestResult class.

  • gh-92734: Allow multi-element reprs emitted by reprlib to be pretty-printed using configurable indentation.

  • gh-92671: Fixed ast.unparse() for empty tuples in the assignment target context.

  • gh-91581: utcfromtimestamp() no longer attempts to resolve fold in the pure Python implementation, since the fold is never 1 in UTC. In addition to being slightly faster in the common case, this also prevents some errors when the timestamp is close to datetime.min. Patch by Paul Ganssle.

  • gh-86388: Removed randrange() functionality deprecated since Python 3.10. Formerly, randrange(10.0) losslessly converted to randrange(10). Now, it raises a TypeError. Also, the exception raised for non-integral values such as randrange(10.5) or randrange(‘10’) has been changed from ValueError to TypeError.

  • gh-90385: Add pathlib.Path.walk() as an alternative to os.walk().

  • gh-92550: Fix pathlib.Path.rglob() for empty pattern.

  • gh-92591: Allow logging filters to return a logging.LogRecord instance so that filters attached to logging.Handlers can enrich records without side effects on other handlers.

  • gh-92445: Fix a bug in argparse where nargs="*" would raise an error instead of returning an empty list when 0 arguments were supplied if choice was also defined in parser.add_argument.

  • gh-92547: Remove undocumented sqlite3 features deprecated in Python 3.10:

    • sqlite3.enable_shared_cache()

    • sqlite3.OptimizedUnicode

    Patch por Erlend E. Aasland.

  • gh-92530: Fix an issue that occurred after interrupting threading.Condition.notify().

  • gh-92531: The statistics.median_grouped() function now always return a float. Formerly, it did not convert the input type when for sequences of length one.

  • gh-84131: The pathlib.Path deprecated method link_to has been removed. Use 3.10’s hardlink_to() method instead as its semantics are consistent with that of symlink_to().

  • gh-89336: Removed configparser module APIs: the SafeConfigParser class alias, the ParsingError.filename property and parameter, and the ConfigParser.readfp method, all of which were deprecated since Python 3.2.

  • gh-92391: Add __class_getitem__() to csv.DictReader and csv.DictWriter, allowing them to be parameterized at runtime. Patch by Marc Mueller.

  • gh-91968: Add SO_RTABLE and SO_USER_COOKIE constants to socket.

  • gh-91810: ElementTree method write() and function tostring() now use the text file’s encoding (“UTF-8” if not available) instead of locale encoding in XML declaration when encoding="unicode" is specified.

  • gh-81790: os.path.splitdrive() now understands DOS device paths with UNC links (beginning \\?\UNC\). Contributed by Barney Gale.

  • gh-91760: Apply more strict rules for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore.

  • gh-90622: Worker processes for concurrent.futures.ProcessPoolExecutor are no longer spawned on demand (a feature added in 3.9) when the multiprocessing context start method is "fork" as that can lead to deadlocks in the child processes due to a fork happening while threads are running.

  • gh-91577: Move imports in SharedMemory methods to module level so that they can be executed late in python finalization.

  • gh-91581: Remove an unhandled error case in the C implementation of calls to datetime.fromtimestamp with no time zone (i.e. getting a local time from an epoch timestamp). This should have no user-facing effect other than giving a possibly more accurate error message when called with timestamps that fall on 10000-01-01 in the local time. Patch by Paul Ganssle.

  • gh-91539: Improve performance of urllib.request.getproxies_environment when there are many environment variables

  • gh-91524: Speed up the regular expression substitution (functions re.sub() and re.subn() and corresponding re.Pattern methods) for replacement strings containing group references by 2–3 times.

  • gh-91447: Fix findtext in the xml module to only give an empty string when the text attribute is set to None.

  • gh-91456: Deprecate current default auto() behavior: In 3.13 the default will be for for auto() to always return the largest member value incremented by 1, and to raise if incompatible value types are used.

  • bpo-47231: Fixed an issue with inconsistent trailing slashes in tarfile longname directories.

  • bpo-39064: zipfile.ZipFile now raises zipfile.BadZipFile instead of ValueError when reading a corrupt zip file in which the central directory offset is negative.

  • bpo-41287: Fix handling of the doc argument in subclasses of property().

  • gh-90005: ctypes dependency libffi is now detected with pkg-config.

  • bpo-32547: The constructors for DictWriter and DictReader now coerce the fieldnames argument to a list if it is an iterator.

  • bpo-35540: Fix dataclasses.asdict() crash when collections.defaultdict is present in the attributes.

  • bpo-47063: Add an index_pages parameter to support using non-default index page names.

  • bpo-47025: Drop support for bytes on sys.path.

  • bpo-46951: Order the contents of zipapp archives, to make builds more reproducible.

  • bpo-42777: Implement pathlib.Path.is_mount() for Windows paths.

  • bpo-46755: In QueueHandler, clear stack_info from LogRecord to prevent stack trace from being written twice.

  • bpo-45393: Fix the formatting for await x and not x in the operator precedence table when using the help() system.

  • bpo-46642: Improve error message when trying to subclass an instance of typing.TypeVar, typing.ParamSpec, typing.TypeVarTuple, etc. Based on patch by Gregory Beauregard.

  • bpo-46364: Restrict use of sockets instead of pipes for stdin of subprocesses created by asyncio to AIX platform only.

  • bpo-28249: Set doctest.DocTest.lineno to None when an object does not have __doc__.

  • bpo-46197: Fix ensurepip environment isolation for subprocess running pip.

  • bpo-45924: Fix asyncio incorrect traceback when future’s exception is raised multiple times. Patch by Kumar Aditya.

  • bpo-45046: Add support of context managers in unittest: methods enterContext() and enterClassContext() of class TestCase, method enterAsyncContext() of class IsolatedAsyncioTestCase and function unittest.enterModuleContext().

  • bpo-44173: Enable fast seeking of uncompressed unencrypted zipfile.ZipExtFile

  • bpo-42627: Fix incorrect parsing of Windows registry proxy settings

  • bpo-42047: Add threading.get_native_id() support for DragonFly BSD. Patch by David Carlier.

  • bpo-14243: The tempfile.NamedTemporaryFile function has a new optional parameter delete_on_close

  • bpo-41246: Give the same callback function for when the overlapped operation is done to the functions recv, recv_into, recvfrom, sendto, send and sendfile inside IocpProactor.

  • bpo-39264: Fixed collections.UserDict.get() to not call __missing__() when a value is not found. This matches the behavior of dict. Patch by Bar Harel.

  • bpo-38693: importlib now uses f-strings internally instead of str.format.

  • bpo-38267: Add timeout parameter to asyncio.loop.shutdown_default_executor(). The default value is None, which means the executor will be given an unlimited amount of time. When called from asyncio.Runner or asyncio.run(), the default timeout is 5 minutes.

  • bpo-34828: sqlite3.Connection.iterdump() now handles databases that use AUTOINCREMENT in one or more tables.

  • bpo-32990: Support reading wave files with the WAVE_FORMAT_EXTENSIBLE format in the wave module.

  • bpo-26253: Allow adjustable compression level for tarfile streams in tarfile.open().

Documentação

  • gh-85525: Remove extra row

  • gh-86404: Deprecated tools make suspicious and rstlint.py are now removed. They have been replaced by sphinx-lint.

  • gh-97741: Fix ! in c domain ref target syntax via a conf.py patch, so it works as intended to disable ref target resolution.

  • gh-96432: Fraction literals now support whitespace around the forward slash, Fraction('2 / 3').

  • gh-96098: Improve discoverability of the higher level concurrent.futures module by providing clearer links from the lower level threading and multiprocessing modules.

  • gh-95957: What’s New 3.11 now has instructions for how to provide compiler and linker flags for Tcl/Tk and OpenSSL on RHEL 7 and CentOS 7.

  • gh-95588: Clarified the conflicting advice given in the ast documentation about ast.literal_eval() being “safe” for use on untrusted input while at the same time warning that it can crash the process. The latter statement is true and is deemed unfixable without a large amount of work unsuitable for a bugfix. So we keep the warning and no longer claim that literal_eval is safe.

  • gh-91207: Fix stylesheet not working in Windows CHM htmlhelp docs and add warning that they are deprecated. Contributed by C.A.M. Gerlach.

  • gh-95454: Replaced incorrectly written true/false values in documentation. Patch by Robert O’Shea

  • gh-95451: Atualiza a documentação da biblioteca com informações de disponibilidade para as plataformas WebAssembly wasm32-emscripten e wasm32-wasi.

  • gh-95415: Use consistent syntax for platform availability. The directive now supports a content body and emits a warning when it encounters an unknown platform.

  • gh-94321: Document the PEP 246 style protocol type sqlite3.PrepareProtocol.

  • gh-86128: Document a limitation in ThreadPoolExecutor where its exit handler is executed before any handlers in atexit.

  • gh-61162: Clarify sqlite3 behavior when How to use the connection context manager.

  • gh-87260: Align sqlite3 argument specs with the actual implementation.

  • gh-86986: The minimum Sphinx version required to build the documentation is now 3.2.

  • gh-88831: Augmented documentation of asyncio.create_task(). Clarified the need to keep strong references to tasks and added a code snippet detailing how to do this.

  • gh-86438: Clarify that -W and PYTHONWARNINGS are matched literally and case-insensitively, rather than as regular expressions, in warnings.

  • gh-93031: Update tutorial introduction output to use 3.10+ SyntaxError invalid range.

  • gh-92240: Added release dates for “What’s New in Python 3.X” for 3.0, 3.1, 3.2, 3.8 and 3.10

  • bpo-47161: Document that pathlib.PurePath does not collapse initial double slashes because they denote UNC paths.

  • bpo-40838: Document that inspect.getdoc(), inspect.getmodule(), and inspect.getsourcefile() might return None.

  • bpo-43689: The Differ documentation now also mentions other whitespace characters, which make it harder to understand the diff output.

  • bpo-38056: Overhaul the Error Handlers documentation in codecs.

  • bpo-13553: Document tkinter.Tk args.

Testes

  • gh-95027: On Windows, when the Python test suite is run with the -jN option, the ANSI code page is now used as the encoding for the stdout temporary file, rather than using UTF-8 which can lead to decoding errors. Patch by Victor Stinner.

  • gh-96624: Fixed the failure of repeated runs of test.test_unittest caused by side effects in test_dotted_but_module_not_loaded.

  • gh-95243: Mitigate the inherent race condition from using find_unused_port() in testSockName() by trying to find an unused port a few times before failing. Patch by Ross Burton.

  • gh-95573: Lib/test/test_asyncio/test_ssl.py exposed a bug in the macOS kernel where intense concurrent load on non-blocking sockets occasionally causes errno.ENOBUFS (“No buffer space available”) to be emitted. FB11063974 filed with Apple, in the mean time as a workaround buffer size used in tests on macOS is decreased to avoid intermittent failures. Patch by Fantix King.

  • gh-95280: Fix problem with test_ssl test_get_ciphers on systems that require perfect forward secrecy (PFS) ciphers.

  • gh-95212: Make multiprocessing test case test_shared_memory_recreate parallel-safe.

  • gh-95218: Move tests for importlib.resources into test_importlib.resources.

  • gh-93963: Updated tests to use preferred location for importlib.resources ABCs.

  • gh-94675: Add a regression test for re exponentional slowdown when using rjsmin.

  • gh-91330: Added more tests for dataclasses to cover behavior with data descriptor-based fields.

  • gh-94208: test_ssl is now checking for supported TLS version and protocols in more tests.

  • gh-94315: Tests now check for DAC override capability instead of relying on os.geteuid().

  • gh-54781: Rename test_tk to test_tkinter, and rename test_ttk_guionly to test_ttk. Patch by Victor Stinner.

  • gh-93839: Move Lib/ctypes/test/ to Lib/test/test_ctypes/. Patch by Victor Stinner.

  • gh-93951: In test_bdb.StateTestCase.test_skip, avoid including auxiliary importers.

  • gh-93957: Provide nicer error reporting from subprocesses in test_venv.EnsurePipTest.test_with_pip.

  • gh-93884: Add test cases for PyNumber_ToBase() that take a large number or a non-int object as parameter.

  • gh-93852: test_asyncio, test_logging, test_socket and test_socketserver now create AF_UNIX domains in the current directory to no longer fail with OSError("AF_UNIX path too long") if the temporary directory (the TMPDIR environment variable) is too long. Patch by Victor Stinner.

  • gh-93353: regrtest now checks if a test leaks temporary files or directories if run with -jN option. Patch by Victor Stinner.

  • gh-84461: run_tests.py now handles cross compiling env vars correctly and pass HOSTRUNNER to regression tests.

  • gh-93616: test_modulefinder now creates a temporary directory in ModuleFinderTest.setUp() instead of module scope.

  • gh-93575: Fix issue with test_unicode test_raiseMemError. The test case now use test.support.calcobjsize to calculate size of PyUnicode structs. sys.getsizeof() may return different size when string has UTF-8 memory.

  • gh-90473: WASI does not have a chmod(2) syscall. os.chmod() is now a dummy function on WASI. Skip all tests that depend on working os.chmod().

  • gh-90473: Skip tests on WASI that require symlinks with absolute paths.

  • gh-57539: Increase calendar test coverage for calendar.LocaleTextCalendar.formatweekday().

  • gh-90473: Skip symlink tests on WASI. wasmtime uses openat2(2) with RESOLVE_BENEATH flag, which prevents symlinks with absolute paths.

  • gh-89858: Fix test_embed for out-of-tree builds. Patch by Kumar Aditya.

  • gh-92886: Fixing tests that fail when running with optimizations (-O) in test_imaplib.py.

  • gh-92886: Fixing tests that fail when running with optimizations (-O) in test_zipimport.py

  • gh-92886: Fixing tests that fail when running with optimizations (-O) in test_py_compile.py

  • gh-92886: Fixing tests that fail when running with optimizations (-O) in test_sys_settrace.py.

  • gh-92886: Fixing tests that fail when running with optimizations (-O) in _test_multiprocessing.py

  • gh-92670: Skip test_shutil.TestCopy.test_copyfile_nonexistent_dir test on AIX as the test uses a trailing slash to force the OS consider the path as a directory, but on AIX the trailing slash has no effect and is considered as a file.

  • gh-92514: Remove unused test.support.BasicTestRunner. Patch by Jelle Zijlstra.

  • bpo-47016: Create a GitHub Actions workflow for verifying bundled pip and setuptools. Patch by Illia Volochii and Adam Turner.

Construção

  • gh-96761: Fix the build process of clang compiler for _bootstrap_python if LTO optimization is applied. Patch by Matthias Görgens and Donghee Na.

  • gh-96883: wasm32-emscripten builds for browsers now include concurrent.futures for asyncio and unittest.mock.

  • gh-85936: CPython now uses the ThinLTO option as the default policy if the Clang compiler accepts the flag. Patch by Donghee Na.

  • gh-96729: Ensure that Windows releases built with Tools\msi\buildrelease.bat are upgradable to and from official Python releases.

  • gh-96269: Shared module targets now depend on new MODULE_DEPS variable, which includes EXPORTSYMS. This fixes a build order issue on unsupported AIX platform.

  • gh-84461: wasm32-emscripten platform no longer builds resource module, getresuid(), getresgid(), and their setters. The APIs are stubs and not functional.

  • gh-95973: Add a new --with-dsymutil configure option to link debug information in macOS. Patch by Pablo Galindo.

  • gh-90536: Use the BOLT post-link optimizer to improve performance, particularly on medium-to-large applications.

  • gh-93744: Remove the configure --with-cxx-main build option: it didn’t work for many years. Remove the MAINCC variable from configure and Makefile. Patch by Victor Stinner.

  • gh-94801: Fix a regression in configure script that caused some header checks to ignore custom CPPFLAGS. The regression was introduced in gh-94802.

  • gh-95145: wasm32-wasi builds no longer depend on WASIX’s pthread stubs. Python now has its own stubbed pthread API.

  • gh-95174: Python now detects missing dup function in WASI and works around some missing errno, select, and socket constants.

  • gh-95174: Python now skips missing socket functions and methods on WASI. WASI can only create sockets from existing fd / accept and has no netdb.

  • gh-95085: Platforms wasm32-unknown-emscripten and wasm32-unknown-wasi have been promoted to PEP 11 tier 3 platform support.

  • gh-94847: Fixed _decimal module build issue on GCC when compiling with LTO and pydebug. Debug builds no longer force inlining of functions.

  • gh-94841: Fix the possible performance regression of PyObject_Free() compiled with MSVC version 1932.

  • gh-94801: configure now uses custom flags like ZLIB_CFLAGS and ZLIB_LIBS when searching for headers and libraries.

  • gh-94773: deepfreeze.py now supports code object with frozensets that contain incompatible, unsortable types.

  • gh-94682: Build and test with OpenSSL 1.1.1q

  • gh-90005: Dependencies of readline and curses module are now detected in configure script with pkg-config. Only ncurses / ncursesw are detected automatically. The old curses library is not configured automatically. Workaround for missing termcap or tinfo library has been removed.

  • gh-90005: Fix building _ctypes extension without pkg-config.

  • gh-90005: _dbm module dependencies are now detected by configure.

  • gh-94404: makesetup now works around an issue with sed on macOS and uses correct CFLAGS for object files that end up in a shared extension. Module CFLAGS are used before PY_STDMODULE_CFLAGS to avoid clashes with system headers.

  • gh-93939: C extension modules are now built by configure and make instead of distutils and setup.py.

  • gh-93939: The 2to3, idle, and pydoc scripts are now generated and installed by Makefile instead of setup.py.

  • gh-94280: Updated pegen regeneration script on Windows to find and use Python 3.9 or higher. Prior to this, pegen regeneration already required 3.9 or higher, but the script may have used lower versions of Python.

  • gh-93584: Address race condition in Makefile when installing a PGO build. All test and install targets now depend on all target.

  • gh-93491: configure now detects and reports PEP 11 support tiers.

  • gh-69093: Fix Modules/Setup.stdlib.in rule for _sqlite3 extension.

  • gh-93207: va_start() with two parameters, like va_start(args, format), is now required to build Python. va_start() is no longer called with a single parameter. Patch by Kumar Aditya.

  • gh-93202: Python now always use the %zu and %zd printf formats to format a size_t or Py_ssize_t number. Building Python 3.12 requires a C11 compiler, so these printf formats are now always supported. Patch by Victor Stinner.

  • gh-90473: Disable pymalloc and increase stack size on wasm32-wasi.

  • bpo-34449: Drop invalid compiler switch -fPIC for HP aCC on HP-UX. Patch by Michael Osipov.

Windows

  • gh-98360: Fixes multiprocessing spawning child processes on Windows from a virtual environment to ensure that child processes that also use multiprocessing to spawn more children will recognize that they are in a virtual environment.

  • gh-98414: Fix py.exe launcher handling of -V:<company>/ option when default preferences have been set in environment variables or configuration files.

  • gh-97728: Fix possible crashes caused by the use of uninitialized variables when pass invalid arguments in os.system() on Windows and in Windows-specific modules (like winreg).

  • gh-90989: Made Gerenciador de instalação do Python install per-user by default (unless an all users install already exists), and clarify some text in the installer.

  • gh-97649: The Tools directory is no longer installed on Windows

  • gh-96965: Update libffi to 3.4.3

  • gh-96577: Fixes a potential buffer overrun in msilib.

  • gh-96559: Fixes the Windows launcher not using the compatible interpretation of default tags found in configuration files when no tag was passed to the command.

  • gh-94781: Fix pcbuild.proj to clean previous instances of output files in Python\deepfreeze and Python\frozen_modules directories on Windows. Patch by Charlie Zhao.

  • gh-89545: Updates platform code getting the Windows version to use native Windows Management Instrumentation (WMI) queries to determine OS version, type, and architecture.

  • gh-95733: Make certain requirements of the Windows Store package optional to allow installing on earlier updates of Windows.

  • gh-95656: Enable the enable_load_extension() sqlite3 API.

  • gh-95587: Fixes some issues where the Windows installer would incorrectly detect certain features of an existing install when upgrading.

  • gh-94399: Restores the behaviour of Gerenciador de instalação do Python for /usr/bin/env shebang lines, which will now search PATH for an executable matching the given command. If none is found, the usual search process is used.

  • gh-95445: Fixes the unsuccessful removal of the HTML document directory when uninstalling with Windows msi.

  • gh-95359: Fix Gerenciador de instalação do Python handling of py.ini commands (it was incorrectly expecting a py_ prefix on keys) and crashes when reading per-user configuration file.

  • gh-95285: Fix Gerenciador de instalação do Python handling of command lines where it is only passed a short executable name.

  • gh-90844: Allow virtual environments to correctly launch when they have spaces in the path.

  • gh-94772: Fix incorrect handling of shebang lines in py.exe launcher

  • gh-94018: zipfile will now remove trailing spaces from path components when extracting files on Windows.

  • gh-93824: Drag and drop of files onto Python files in Windows Explorer has been enabled for Windows ARM64.

  • gh-43414: os.get_terminal_size() now attempts to read the size from any provided handle, rather than only supporting file descriptors 0, 1 and 2.

  • gh-92817: Ensures that py.exe will prefer an active virtual environment over default tags specified with environment variables or through a py.ini file.

  • gh-92984: Explicitly disable incremental linking for non-Debug builds

  • gh-92841: asyncio no longer throws RuntimeError: Event loop is closed on interpreter exit after asynchronous socket activity. Patch by Oleg Iarygin.

  • bpo-46907: Update Windows installer to use SQLite 3.38.4.

  • gh-91061: Accept os.PathLike for the argument to winsound.PlaySound

  • bpo-42658: Support native Windows case-insensitive path comparisons by using LCMapStringEx instead of str.lower() in ntpath.normcase(). Add LCMapStringEx to the _winapi module.

  • bpo-38704: Prevent installation on unsupported Windows versions.

macOS

  • gh-97897: The macOS 13 SDK includes support for the mkfifoat and mknodat system calls. Using the dir_fd option with either os.mkfifo() or os.mknod() could result in a segfault if cpython is built with the macOS 13 SDK but run on an earlier version of macOS. Prevent this by adding runtime support for detection of these system calls (“weaklinking”) as is done for other newer syscalls on macOS.

IDLE

  • gh-97527: Fix a bug in the previous bugfix that caused IDLE to not start when run with 3.10.8, 3.12.0a1, and at least Microsoft Python 3.10.2288.0 installed without the Lib/test package. 3.11.0 was never affected.

  • gh-65802: Document handling of extensions in Save As dialogs.

  • gh-95191: Include prompts when saving Shell (interactive input and output).

  • gh-95511: Fix the Shell context menu copy-with-prompts bug of copying an extra line when one selects whole lines.

  • gh-95471: In the Edit menu, move Select All and add a new separator.

  • gh-95411: Enable using IDLE’s module browser with .pyw files.

  • gh-89610: Add .pyi as a recognized extension for IDLE on macOS. This allows opening stub files by double clicking on them in the Finder.

Ferramentas/Demos

  • gh-68686: Remove ptags and eptags scripts.

  • gh-97681: Remove the Tools/demo/ directory which contained old demo scripts. A copy can be found in the old-demos project. Patch by Victor Stinner.

  • gh-97669: Remove outdated example scripts of the Tools/scripts/ directory. A copy can be found in the old-demos project. Patch by Victor Stinner.

  • gh-95853: The wasm_build.py script now pre-builds Emscripten ports, checks for broken EMSDK versions, and warns about pkg-config env vars.

  • gh-95853: A nova ferramenta Tools/wasm/wasm_builder.py automatiza as etapas de configuração, compilação e teste para a construção do CPython em plataformas WebAssembly.

  • gh-95731: Fix handling of module docstrings in Tools/i18n/pygettext.py.

  • gh-93939: Add script Tools/scripts/check_modules.py to check and validate builtin and shared extension modules. The script also handles Modules/Setup and will eventually replace setup.py.

  • gh-94538: Fix Argument Clinic output to custom file destinations. Patch by Erlend E. Aasland.

  • gh-94430: Allow parameters named module and self with custom C names in Argument Clinic. Patch by Erlend E. Aasland

  • gh-86087: The Tools/scripts/parseentities.py script used to parse HTML4 entities has been removed.

API C

Python 3.11.0 beta 1

Data de lançamento: 2022-05-06

Segurança

  • gh-57684: Add the -P command line option and the PYTHONSAFEPATH environment variable to not prepend a potentially unsafe path to sys.path. Patch by Victor Stinner.

Núcleo e embutidos

  • gh-89519: Chaining classmethod descriptors (introduced in bpo-19072) is deprecated. It can no longer be used to wrap other descriptors such as property(). The core design of this feature was flawed, and it caused a number of downstream problems.

  • gh-92345: pymain_run_python() now imports readline and rlcompleter before sys.path is extended to include the current working directory of an interactive interpreter. Non-interactive interpreters are not affected.

  • bpo-43857: Improve the AttributeError message when deleting a missing attribute. Patch by Géry Ogam.

  • gh-92245: Make sure that PEP 523 is respected in all cases. In 3.11a7, specialization may have prevented Python-to-Python calls respecting PEP 523.

  • gh-92203: Add a closure keyword-only parameter to exec(). It can only be specified when exec-ing a code object that uses free variables. When specified, it must be a tuple, with exactly the number of cell variables referenced by the code object. closure has a default value of None, and it must be None if the code object doesn’t refer to any free variables.

  • gh-91173: Disable frozen modules in debug builds. Patch by Kumar Aditya.

  • gh-92114: Improve error message when subscript a type with __class_getitem__ set to None.

  • gh-92112: Fix crash triggered by an evil custom mro() on a metaclass.

  • gh-92063: The PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS instruction now ensures methods are called only on objects of the correct type.

  • gh-92031: Deoptimize statically allocated code objects during Py_FINALIZE() so that future _PyCode_Quicken calls always start with unquickened code.

  • gh-92036: Fix a crash in subinterpreters related to the garbage collector. When a subinterpreter is deleted, untrack all objects tracked by its GC. To prevent a crash in deallocator functions expecting objects to be tracked by the GC, leak a strong reference to these objects on purpose, so they are never deleted and their deallocator functions are not called. Patch by Victor Stinner.

  • gh-92032: The interpreter can now autocomplete soft keywords, as of now match, case, and _ (wildcard pattern) from PEP 634.

  • gh-87999: The warning emitted by the Python parser for a numeric literal immediately followed by keyword has been changed from deprecation warning to syntax warning.

  • gh-91869: Fix an issue where specialized opcodes with extended arguments could produce incorrect tracing output or lead to assertion failures.

  • gh-91603: Speed up types.UnionType instantiation. Based on patch provided by Yurii Karabas.

  • gh-89373: If Python is built in debug mode, Python now ensures that deallocator functions leave the current exception unchanged. Patch by Victor Stinner.

  • gh-91632: Fix a minor memory leak at exit: release the memory of the generic_alias_iterator type. Patch by Donghee Na.

  • gh-81548: Octal escapes with value larger than 0o377 now produce a DeprecationWarning. In a future Python version they will be a SyntaxWarning and eventually a SyntaxError.

  • bpo-43950: Use a single compact table for line starts, ends and column offsets. Reduces memory consumption for location info by half

  • gh-91102: Use Argument Clinic for EncodingMap. Patch by Oleg Iarygin.

  • gh-91636: Fixed a crash in a garbage-collection edge-case, in which a PyFunction_Type.tp_clear function could leave a python function object in an inconsistent state.

  • gh-91603: Speed up isinstance() and issubclass() checks for types.UnionType. Patch by Yurii Karabas.

  • gh-91625: Fixed a bug in which adaptive opcodes ignored any preceding EXTENDED_ARGs on specialization failure.

  • gh-78607: The LLTRACE special build now looks for the name __lltrace__ defined in module globals, rather than the name __ltrace__, which had been introduced as a typo.

  • gh-91576: Speed up iteration of ascii strings by 50%. Patch by Kumar Aditya.

  • gh-89279: Improve interpreter performance on Windows by inlining a few specific macros.

  • gh-91502: Add a new _PyFrame_IsEntryFrame() API function, to check if a PyFrameObject is an entry frame. Patch by Pablo Galindo.

  • gh-91266: Refactor the bytearray strip methods strip, lstrip and rstrip to use a common implementation.

  • gh-91479: Replaced the __note__ field of BaseException (added in an earlier version of 3.11) with the final design of PEP 678. Namely, BaseException gets an add_note() method, and its __notes__ field is created when necessary.

  • gh-46055: Speed up right shift of negative integers, by removing unnecessary creation of temporaries. Original patch by Xinhang Xu, reworked by Mark Dickinson.

  • gh-91462: Make the interpreter’s low-level tracing (lltrace) feature output more readable by displaying opcode names (rather than just numbers), and by displaying stack contents before each opcode.

  • gh-89455: Fixed an uninitialized bool value in the traceback printing code path that was introduced by the initial bpo-45292 exception groups work.

  • gh-91421: Fix a potential integer overflow in _Py_DecodeUTF8Ex.

  • gh-91428: Add static const char *const _PyOpcode_OpName[256] = {...}; to opcode.h for debug builds to assist in debugging the Python interpreter. It is now more convenient to make various forms of debugging output more human-readable by including opcode names rather than just the corresponding decimal digits.

  • bpo-47120: Make POP_JUMP_IF_TRUE, POP_JUMP_IF_FALSE, POP_JUMP_IF_NONE and POP_JUMP_IF_NOT_NONE virtual, mapping to new relative jump opcodes.

  • bpo-45317: Add internal documentation explaining design of new (for 3.11) frame stack.

Biblioteca

  • bpo-47197: ctypes used to mishandle void return types, so that for instance a function declared like ctypes.CFUNCTYPE(None, ctypes.c_int) would be called with signature int f(int) instead of void f(int). Wasm targets require function pointers to be called with the correct signatures so this led to crashes. The problem is now fixed.

Núcleo e embutidos

  • bpo-47120: Make opcodes JUMP_IF_TRUE_OR_POP and JUMP_IF_FALSE_OR_POP relative rather than absolute.

  • bpo-47177: Replace the f_lasti member of the internal _PyInterpreterFrame structure with a prev_instr pointer, which reduces overhead in the main interpreter loop. The f_lasti attribute of Python-layer frame objects is preserved for backward-compatibility.

  • bpo-46961: Integer mod/remainder operations, including the three-argument form of pow(), now consistently return ints from the global small integer cache when applicable.

  • bpo-46962: Classes and functions that unconditionally declared their docstrings ignoring the --without-doc-strings compilation flag no longer do so.

    The classes affected are ctypes.UnionType, pickle.PickleBuffer, testcapi.RecursingInfinitelyError, and types.GenericAlias.

    The functions affected are 24 methods in ctypes.

    Patch by Oleg Iarygin.

  • bpo-46942: Use Argument Clinic for the types.MethodType constructor. Patch by Oleg Iarygin.

  • bpo-46764: Fix wrapping bound methods with @classmethod

  • bpo-43464: Optimize set.intersection() for non-set arguments.

  • bpo-46721: Optimize set.issuperset() for non-set argument.

  • bpo-46509: Add type-specialized versions of the Py_DECREF(), and use them for float, int, str, bool, and None to avoid pointer-chasing at runtime where types are known at C compile time.

Construção

  • bpo-46045: Do not use POSIX semaphores on NetBSD

Núcleo e embutidos

  • bpo-36819: Fix crashes in built-in encoders with error handlers that return position less or equal than the starting position of non-encodable characters.

  • bpo-34093: marshal.dumps() uses FLAG_REF for all interned strings. This makes output more deterministic and helps reproducible build.

  • bpo-26579: Added object.__getstate__ which provides the default implementation of the __getstate__() method.

    Copying and pickling instances of subclasses of builtin types bytearray, set, frozenset, collections.OrderedDict, collections.deque, weakref.WeakSet, and datetime.tzinfo now copies and pickles instance attributes implemented as slots.

Biblioteca

  • gh-87901: Add the encoding parameter to os.popen().

  • gh-90997: Fix an issue where dis utilities may interpret populated inline cache entries as valid instructions.

  • gh-92332: Deprecate typing.Text (removal of the class is currently not planned). Patch by Alex Waygood.

  • gh-78157: Deprecate nested classes in enum definitions becoming members – in 3.13 they will be normal classes; add member and nonmember functions to allow control over results now.

  • gh-92356: Fixed a performance regression in ctypes function calls.

  • gh-90997: Show the actual named values stored in inline caches when show_caches=True is passed to dis utilities.

  • gh-92301: Prefer close_range() to iterating over procfs for file descriptor closing in subprocess for better performance.

  • gh-67248: Sort the miscellaneous topics in Cmd.do_help()

  • gh-92210: Port socket.__init__ to Argument Clinic. Patch by Cinder.

  • gh-80010: Add support for generalized ISO 8601 parsing to datetime.datetime.fromisoformat(), datetime.date.fromisoformat() and datetime.time.fromisoformat(). Patch by Paul Ganssle.

  • gh-92118: Fix a 3.11 regression in contextmanager(), which caused it to propagate exceptions with incorrect tracebacks.

  • gh-90887: Adding COPYFILE_STAT, COPYFILE_ACL and COPYFILE_XATTR constants for os.fcopyfile() available in macOs.

  • gh-91215: For @dataclass, add weakref_slot. The new parameter defaults to False. If true, and if slots=True, add a slot named "__weakref__", which will allow instances to be weakref’d. Contributed by Eric V. Smith

  • gh-85984: New function os.login_tty() for Unix.

  • gh-92128: Add __class_getitem__() to logging.LoggerAdapter and logging.StreamHandler, allowing them to be parameterized at runtime. Patch by Alex Waygood.

  • gh-92049: Forbid pickling constants re._constants.SUCCESS etc. Previously, pickling did not fail, but the result could not be unpickled.

  • gh-92062: inspect.Parameter now raises ValueError if name is a keyword, in addition to the existing check that it is an identifier.

  • gh-87390: Add an __unpacked__ attribute to types.GenericAlias. Patch by Jelle Zijlstra.

  • gh-88089: Add support for generic typing.NamedTuple.

  • gh-91996: New http.HTTPMethod enum to represent all the available HTTP request methods in a convenient way

  • gh-91984: Modified test strings in test_argparse.py to not contain trailing spaces before end of line.

  • gh-91952: Add encoding="locale" support to TextIOWrapper.reconfigure().

  • gh-91954: Add encoding and errors arguments to subprocess.getoutput() and subprocess.getstatusoutput().

  • bpo-47029: Always close the read end of the pipe used by multiprocessing.Queue after the last write of buffered data to the write end of the pipe to avoid BrokenPipeError at garbage collection and at multiprocessing.Queue.close() calls. Patch by Géry Ogam.

  • gh-91928: Add datetime.UTC alias for datetime.timezone.utc.

    Patch by Kabir Kwatra.

  • gh-68966: The mailcap module is now deprecated and will be removed in Python 3.13. See PEP 594 for the rationale and the mimetypes module for an alternative. Patch by Victor Stinner.

  • gh-91401: Provide a way to disable subprocess use of vfork() just in case it is ever needed and document the existing mechanism for posix_spawn().

  • gh-64783: Fix signal.NSIG value on FreeBSD to accept signal numbers greater than 32, like signal.SIGRTMIN and signal.SIGRTMAX. Patch by Victor Stinner.

  • gh-91910: Add missing f prefix to f-strings in error messages from the multiprocessing and asyncio modules.

  • gh-91860: Add typing.dataclass_transform(), implementing PEP 681. Patch by Jelle Zijlstra.

  • gh-91832: Add required attribute to argparse.Action repr output.

  • gh-91827: In the tkinter module add method info_patchlevel() which returns the exact version of the Tcl library as a named tuple similar to sys.version_info.

  • gh-84461: Add --enable-wasm-pthreads to enable pthreads support for WASM builds. Emscripten/node no longer has threading enabled by default. Include additional file systems.

  • gh-91821: Fix unstable test_from_tuple test in test_decimal.py.

  • gh-91217: Deprecate the xdrlib module.

  • gh-91217: Deprecate the uu module.

  • gh-91760: More strict rules will be applied for numerical group references and group names in regular expressions. For now, a deprecation warning is emitted for group references and group names which will be errors in future Python versions.

  • gh-84461: Add provisional sys._emscripten_info named tuple with build-time and run-time information about Emscripten platform.

  • gh-90623: signal.raise_signal() and os.kill() now check immediately for pending signals. Patch by Victor Stinner.

  • gh-91734: Fix OSS audio support on Solaris.

  • gh-90633: Include the passed value in the exception thrown by typing.assert_never(). Patch by Jelle Zijlstra.

  • gh-91700: Compilation of regular expression containing a conditional expression (?(group)...) now raises an appropriate re.error if the group number refers to not defined group. Previously an internal RuntimeError was raised.

  • gh-91231: Add an optional keyword shutdown_timeout parameter to the multiprocessing.BaseManager constructor. Kill the process if terminate() takes longer than the timeout. Patch by Victor Stinner.

  • gh-91621: Fix typing.get_type_hints() for collections.abc.Callable. Patch by Shantanu Jain.

  • gh-90568: Parsing \N escapes of Unicode Named Character Sequences in a regular expression raises now re.error instead of TypeError.

  • gh-91670: Remove deprecated SO config variable in sysconfig.

  • gh-91217: Deprecate the telnetlib module.

  • gh-91217: Deprecate the sunau module.

  • gh-91217: Deprecate the spwd module.

  • gh-91217: Deprecate the sndhdr module, as well as inline needed functionality for email.mime.MIMEAudio.

  • gh-91616: re module, fix fullmatch() mismatch when using Atomic Grouping or Possessive Quantifiers.

  • gh-91217: Deprecate the ‘pipes’ module.

  • gh-91217: Deprecate the ossaudiodev module.

  • bpo-47256: re module, limit the maximum capturing group to 1,073,741,823 in 64-bit build, this increases the depth of backtracking.

  • gh-91217: Deprecate the nis module.

  • gh-91595: Fix the comparison of character and integer inside Tools.gdb.libpython.write_repr(). Patch by Yu Liu.

  • gh-74166: Add option to raise all errors from create_connection() in an ExceptionGroup when it fails to create a connection. The default remains to raise only the last error that had occurred when multiple addresses were tried.

  • gh-91487: Optimize asyncio UDP speed, over 100 times faster when transferring a large file.

  • gh-91575: Update case-insensitive matching in the re module to the latest Unicode version.

  • gh-90622: In concurrent.futures.process.ProcessPoolExecutor disallow the “fork” multiprocessing start method when the new max_tasks_per_child feature is used as the mix of threads+fork can hang the child processes. Default to using the safe “spawn” start method in that circumstance if no mp_context was supplied.

  • gh-89022: In sqlite3, SQLITE_MISUSE result codes are now mapped to InterfaceError instead of ProgrammingError. Also, more accurate exceptions are raised when binding parameters fail. Patch by Erlend E. Aasland.

  • gh-91526: Stop calling os.device_encoding(file.fileno()) in TextIOWrapper. It was complex, never documented, and didn’t work for most cases. (Patch by Inada Naoki.)

  • gh-88116: Change the frame-related functions in the inspect module to return a regular object (that is backwards compatible with the old tuple-like interface) that include the extended PEP 657 position information (end line number, column and end column). The affected functions are: inspect.getframeinfo(), inspect.getouterframes(), inspect.getinnerframes(), inspect.stack() and inspect.trace(). Patch by Pablo Galindo.

  • gh-69093: Add indexing and slicing support to sqlite3.Blob. Patch by Aviv Palivoda and Erlend E. Aasland.

  • gh-69093: Add context manager support to sqlite3.Blob. Patch by Aviv Palivoda and Erlend E. Aasland.

  • gh-91217: Deprecate nntplib.

  • gh-91217: Deprecate msilib.

  • gh-91404: Improve the performance of re matching by using computed gotos (or “threaded code”) on supported platforms and removing expensive pointer indirections.

  • gh-91217: Deprecate the imghdr module.

  • gh-91217: Deprecate the crypt module.

  • gh-91276: Make space for longer opcodes in dis output.

  • bpo-47000: Make TextIOWrapper uses locale encoding when encoding="locale" is specified even in UTF-8 mode.

  • gh-91230: warnings.catch_warnings() now accepts arguments for warnings.simplefilter(), providing a more concise way to locally ignore warnings or convert them to errors.

  • gh-91217: Deprecate the chunk module.

  • gh-91498: Add the TCP_CONNECTION_INFO option (available on macOS) to socket.

  • bpo-47260: Fix os.closerange() potentially being a no-op in a Linux seccomp sandbox.

  • bpo-47087: Implement typing.Required and typing.NotRequired (PEP 655). Patch by David Foster and Jelle Zijlstra.

  • bpo-47061: Deprecate cgi and cgitb.

  • bpo-47061: Deprecate audioop.

  • bpo-47000: Add locale.getencoding() to get the current locale encoding. It is similar to locale.getpreferredencoding(False) but ignores the Python UTF-8 Mode.

  • bpo-42012: Add wsgiref.types, containing WSGI-specific types for static type checking.

  • bpo-47227: Suppress expression chaining for more re parsing errors.

  • bpo-47211: Remove undocumented and never working function re.template() and flag re.TEMPLATE. This was later reverted in 3.11.0b2 and deprecated instead.

  • bpo-47135: decimal.localcontext() now accepts context attributes via keyword arguments

  • bpo-43323: Fix errors in the email module if the charset itself contains undecodable/unencodable characters.

  • bpo-46841: Disassembly of quickened code.

  • bpo-46681: Forward gzip.compress() compresslevel to zlib.

  • bpo-45100: Add typing.get_overloads() and typing.clear_overloads(). Patch by Jelle Zijlstra.

  • bpo-44807: typing.Protocol no longer silently replaces __init__() methods defined on subclasses. Patch by Adrian Garcia Badaracco.

  • bpo-46787: Fix concurrent.futures.ProcessPoolExecutor exception memory leak

  • bpo-46720: Add support for path-like objects to multiprocessing.set_executable() for Windows to be on a par with Unix-like systems. Patch by Géry Ogam.

  • bpo-46696: Add SO_INCOMING_CPU constant to socket.

  • bpo-46053: Fix OSS audio support on NetBSD.

  • bpo-45639: image/avif and image/webp were added to mimetypes.

  • bpo-46285: Add command-line option -p/--protocol to module http.server which specifies the HTTP version to which the server is conformant (HTTP/1.1 conformant servers can now be run from the command-line interface of module http.server). Patch by Géry Ogam.

  • bpo-44791: Accept ellipsis as the last argument of typing.Concatenate.

  • bpo-46547: Remove variables leaking into pydoc.Helper class namespace.

  • bpo-46415: Fix ipaddress.ip_{address,interface,network} raising TypeError instead of ValueError if given invalid tuple as address parameter.

  • bpo-46075: CookieJar with DefaultCookiePolicy now can process cookies from localhost with domain=localhost explicitly specified in Set-Cookie header.

  • bpo-45995: Add a “z” option to the string formatting specification that coerces negative zero floating-point values to positive zero after rounding to the format precision. Contributed by John Belmonte.

  • bpo-26175: Fully implement the io.BufferedIOBase or io.TextIOBase interface for tempfile.SpooledTemporaryFile objects. This lets them work correctly with higher-level layers (like compression modules). Patch by Carey Metcalfe.

  • bpo-45138: Fix a regression in the sqlite3 trace callback where bound parameters were not expanded in the passed statement string. The regression was introduced in Python 3.10 by bpo-40318. Patch by Erlend E. Aasland.

  • bpo-44863: Allow TypedDict subclasses to also include Generic as a base class in class based syntax. Thereby allowing the user to define a generic TypedDict, just like a user-defined generic but with TypedDict semantics.

  • bpo-44587: Fix BooleanOptionalAction to not automatically add a default string. If a default string is desired, use a formatter to add it.

  • bpo-43827: All positional-or-keyword parameters to ABCMeta.__new__ are now positional-only to avoid conflicts with keyword arguments to be passed to __init_subclass__().

  • bpo-43218: Prevent creation of a venv whose path contains the PATH separator. This could affect the usage of the activate script. Patch by Dustin Rodrigues.

  • bpo-38435: Add a process_group parameter to subprocess.Popen to help move more things off of the unsafe preexec_fn parameter.

  • bpo-42066: Fix cookies getting sorted in CookieJar.__iter__() which is an extra behavior and not mentioned in RFC 2965 or Netscape cookie protocol. Now the cookies in CookieJar follows the order of the Set-Cookie header. Patch by Iman Kermani.

  • bpo-40617: Add create_window_function() to sqlite3.Connection for creating aggregate window functions. Patch by Erlend E. Aasland.

  • bpo-40676: Convert csv to use Argument Clinic for csv.field_size_limit(), csv.get_dialect(), csv.unregister_dialect() and csv.list_dialects().

  • bpo-39716: Raise an ArgumentError when the same subparser name is added twice to an argparse.ArgumentParser. This is consistent with the (default) behavior when the same option string is added twice to an ArgumentParser.

  • bpo-36073: Raise ProgrammingError instead of segfaulting on recursive usage of cursors in sqlite3 converters. Patch by Sergey Fedoseev.

  • bpo-34975: Adds a start_tls() method to StreamWriter, which upgrades the connection with TLS using the given SSLContext.

  • bpo-22276: Path methods glob() and rglob() return only directories if pattern ends with a pathname components separator (/ or sep). Patch by Eisuke Kawashima.

  • bpo-24905: Add blobopen() to sqlite3.Connection. sqlite3.Blob allows incremental I/O operations on blobs. Patch by Aviv Palivoda and Erlend E. Aasland.

Documentação

Testes

  • gh-92169: Use warnings_helper.import_deprecated() to import deprecated modules uniformly in tests. Patch by Hugo van Kemenade.

  • gh-84461: When multiprocessing is enabled, libregrtest can now use a Python executable other than sys.executable via the --python flag.

  • gh-91904: Fix initialization of PYTHONREGRTEST_UNICODE_GUARD which prevented running regression tests on non-UTF-8 locale.

  • gh-91752: Added @requires_zlib to test.test_tools.test_freeze.TestFreeze.

  • gh-91607: Fix test_concurrent_futures to test the correct multiprocessing start method context in several cases where the test logic mixed this up.

  • bpo-40280: Threading tests are now skipped on WASM targets without pthread support.

  • bpo-47109: Test for ctypes.macholib.dyld, ctypes.macholib.dylib, and ctypes.macholib.framework are brought from manual pre-unittest times to ctypes.test location and structure. Patch by Oleg Iarygin.

  • bpo-29890: Add tests for ipaddress.IPv4Interface and ipaddress.IPv6Interface construction with tuple arguments. Original patch and tests by louisom.

Construção

  • gh-89452: gdbm-compat is now preferred over ndbm if both are available on the system. This allows avoiding the problematic ndbm.h on macOS.

  • gh-91731: Python is now built with -std=c11 compiler option, rather than -std=c99. Patch by Victor Stinner.

  • bpo-47152: Add script and make target for generating sre_constants.h.

  • bpo-47103: As construções de PGInstrument do Windows agora copiam uma DLL necessária para o diretório de saída, facilitando a execução do estágio de perfil de uma construção do PGO.

Windows

  • bpo-46907: Update Windows installer to use SQLite 3.38.3.

  • bpo-47239: Fixed –list and –list-paths output for Gerenciador de instalação do Python when used in an active virtual environment.

  • bpo-46907: Update Windows installer to use SQLite 3.38.2.

  • bpo-46785: Fix race condition between os.stat() and unlinking a file on Windows, by using errors codes returned by FindFirstFileW() when appropriate in win32_xstat_impl.

  • bpo-40859: Update Windows build to use xz-5.2.5

macOS

  • bpo-46907: Update macOS installer to SQLite 3.38.4.

Ferramentas/Demos

  • gh-91583: Fix regression in the code generated by Argument Clinic for functions with the defining_class parameter.

  • gh-91575: Add script Tools/scripts/generate_re_casefix.py and the make target regen-re for generating additional data for case-insensitive matching according to the current Unicode version.

  • gh-91551: Remove the ancient Pynche color editor. It has moved to https://gitlab.com/warsaw/pynche

API C

Python 3.11.0 alpha 7

Data de lançamento: 2022-04-05

Núcleo e embutidos

  • bpo-47212: Raise IndentationError instead of SyntaxError for a bare except with no following indent. Improve SyntaxError locations for an un-parenthesized generator used as arguments. Patch by Matthieu Dartiailh.

  • bpo-47186: Replace JUMP_IF_NOT_EG_MATCH by CHECK_EG_MATCH + jump.

  • bpo-47176: Emscripten builds cannot handle signals in the usual way due to platform limitations. Python can now handle signals. To use, set Module.Py_EmscriptenSignalBuffer to be a single byte SharedArrayBuffer and set Py_EMSCRIPTEN_SIGNAL_HANDLING to 1. Writing a number into the SharedArrayBuffer will cause the corresponding signal to be raised into the Python thread.

  • bpo-47186: Replace JUMP_IF_NOT_EXC_MATCH by CHECK_EXC_MATCH + jump.

  • bpo-47120: Replace the absolute jump opcode JUMP_NO_INTERRUPT by the relative JUMP_BACKWARD_NO_INTERRUPT.

  • bpo-46841: Avoid unnecessary allocations when comparing code objects.

  • bpo-47182: Fix a crash when using a named unicode character like "\N{digit nine}" after the main interpreter has been initialized a second time.

  • bpo-47162: O WebAssembly não consegue lidar com conversões de ponteiros para função ruins (contagem ou tipos diferentes de argumento). O Python agora pode usar trampolins de chamada para atenuar o problema. Defina PY_CALL_TRAMPOLINE para ativar os trampolins de chamada.

  • bpo-46775: Some Windows system error codes(>= 10000) are now mapped into the correct errno and may now raise a subclass of OSError. Patch by Donghee Na.

  • bpo-47129: Improve error messages in f-string syntax errors concerning empty expressions.

  • bpo-47117: Fix a crash if we fail to decode characters in interactive mode if the tokenizer buffers are uninitialized. Patch by Pablo Galindo.

  • bpo-47127: Speed up calls to c functions with keyword arguments by 25% with specialization. Patch by Kumar Aditya.

  • bpo-47120: Replaced JUMP_ABSOLUTE by the relative jump JUMP_BACKWARD.

  • bpo-42197: PyFrame_FastToLocalsWithError() and PyFrame_LocalsToFast() are no longer called during profiling nor tracing. C code can access the f_locals attribute of PyFrameObject by calling PyFrame_GetLocals().

  • bpo-47070: Improve performance of array_inplace_repeat by reducing the number of invocations of memcpy. Refactor the repeat and inplace repeat methods of array, bytes, bytearray and unicodeobject to use the common _PyBytes_Repeat.

  • bpo-47053: Reduce de-optimization in the specialized BINARY_OP_INPLACE_ADD_UNICODE opcode.

  • bpo-47045: Remove the f_state field from the _PyInterpreterFrame struct. Add the owner field to the _PyInterpreterFrame struct to make ownership explicit to simplify clearing and deallocing frames and generators.

Biblioteca

  • bpo-46968: Check for the existence of the “sys/auxv.h” header in faulthandler to avoid compilation problems in systems where this header doesn’t exist. Patch by Pablo Galindo

Núcleo e embutidos

  • bpo-46329: Use low bit of LOAD_GLOBAL to indicate whether to push a NULL before the global. Helps streamline the call sequence a bit.

  • bpo-46841: Quicken bytecode in-place by storing it as part of the corresponding PyCodeObject.

  • bpo-47012: Speed up iteration of bytes and bytearray by 30%. Patch by Kumar Aditya.

  • bpo-47009: Improved the performance of list.append() and list comprehensions by optimizing for the common case, where no resize is needed. Patch by Dennis Sweeney.

  • bpo-47005: Improve performance of bytearray_repeat and bytearray_irepeat by reducing the number of invocations of memcpy.

Biblioteca

Núcleo e embutidos

  • bpo-46993: Speed up bytearray creation from list and tuple by 40%. Patch by Kumar Aditya.

  • bpo-39829: Removed the __len__() call when initializing a list and moved initializing to list_extend. Patch by Jeremiah Pascual.

  • bpo-46944: Speed up throwing exception in generator with METH_FASTCALL calling convention. Patch by Kumar Aditya.

  • bpo-46841: Modify STORE_SUBSCR to use an inline cache entry (rather than its oparg) as an adaptive counter.

  • bpo-46841: Use inline caching for PRECALL and CALL, and remove the internal machinery for managing the (now unused) non-inline caches.

  • bpo-46881: Statically allocate and initialize the latin1 characters.

  • bpo-46838: Improve syntax errors for incorrect function definitions. Patch by Pablo Galindo

  • bpo-43721: Fix docstrings of getter, setter, and deleter to clarify that they create a new copy of the property.

  • bpo-43224: Make grammar changes required for PEP 646.

Biblioteca

  • bpo-47208: Allow vendors to override CTYPES_MAX_ARGCOUNT.

  • bpo-23689: re module: fix memory leak when a match is terminated by a signal or memory allocation failure. Patch by Ma Lin.

  • bpo-47167: Allow overriding a future compliance check in asyncio.Task.

  • bpo-47151: When subprocess tries to use vfork, it now falls back to fork if vfork returns an error. This allows use in situations where vfork isn’t allowed by the OS kernel.

  • bpo-47152: Convert the re module into a package. Deprecate modules sre_compile, sre_constants and sre_parse.

  • bpo-4833: Add ZipFile.mkdir()

  • bpo-27929: Fix asyncio.loop.sock_connect() to only resolve names for socket.AF_INET or socket.AF_INET6 families. Resolution may not make sense for other families, like socket.AF_BLUETOOTH and socket.AF_UNIX.

  • bpo-14265: Adds the fully qualified test name to unittest output

  • bpo-47061: Deprecate the aifc module.

  • bpo-39622: Handle Ctrl+C in asyncio programs to interrupt the main task.

  • bpo-47101: hashlib.algorithms_available now lists only algorithms that are provided by activated crypto providers on OpenSSL 3.0. Legacy algorithms are not listed unless the legacy provider has been loaded into the default OSSL context.

  • bpo-47099: All URLError exception messages raised in urllib.request.URLopener now contain a colon between ftp error and the rest of the message. Previously, open_ftp() missed the colon. Patch by Oleg Iarygin.

  • bpo-47099: Exception chaining is changed from Exception.with_traceback()/sys.exc_info() to PEP 3134. Patch by Oleg Iarygin.

  • bpo-47095: hashlib’s internal _blake2 module now prefers libb2 from https://www.blake2.net/ over Python’s vendored copy of blake2.

  • bpo-47098: The Keccak Code Package for hashlib’s internal _sha3 module has been replaced with tiny_sha3. The module is used as fallback when Python is built without OpenSSL.

  • bpo-47088: Implement typing.LiteralString, part of PEP 675. Patch by Jelle Zijlstra.

  • bpo-42885: Optimize re.search(), re.split(), re.findall(), re.finditer() and re.sub() for regular expressions starting with \A or ^.

  • bpo-23691: Protect the re.finditer() iterator from re-entering.

  • bpo-47067: Optimize calling GenericAlias objects by using PEP 590 vectorcall and by replacing PyObject_SetAttrString with PyObject_SetAttr.

  • bpo-28080: Add the metadata_encoding parameter in the zipfile.ZipFile constructor and the --metadata-encoding option in the zipfile CLI to allow reading zipfiles using non-standard codecs to encode the filenames within the archive.

  • bpo-47000: Make io.text_encoding() returns “utf-8” when UTF-8 mode is enabled.

  • bpo-42369: Fix thread safety of zipfile._SharedFile.tell() to avoid a “zipfile.BadZipFile: Bad CRC-32 for file” exception when reading a ZipFile from multiple threads.

  • bpo-38256: Fix binascii.crc32() when it is compiled to use zlib’c crc32 to work properly on inputs 4+GiB in length instead of returning the wrong result. The workaround prior to this was to always feed the function data in increments smaller than 4GiB or to just call the zlib module function.

    We also have binascii.crc32() release the GIL when computing on larger inputs as zlib.crc32() and hashlib do.

    This also boosts performance on Windows as it now uses the zlib crc32 implementation for binascii.crc32() for a 2-3x speedup.

    That the stdlib has a crc32 API in two modules is a known historical oddity. This moves us closer to a single implementation behind them.

  • bpo-47066: Global inline flags (e.g. (?i)) can now only be used at the start of the regular expressions. Using them not at the start of expression was deprecated since Python 3.6.

  • bpo-39394: A warning about inline flags not at the start of the regular expression now contains the position of the flag.

  • bpo-433030: Add support of atomic grouping ((?>...)) and possessive quantifiers (*+, ++, ?+, {m,n}+) in regular expressions.

  • bpo-47062: Implement asyncio.Runner context manager.

  • bpo-46382: dataclass() slots=True now correctly omits slots already defined in base classes. Patch by Arie Bovenberg.

  • bpo-47057: Use FASTCALL convention for FutureIter.throw()

  • bpo-47061: Deprecate the various modules listed by PEP 594:

    aifc, asynchat, asyncore, audioop, cgi, cgitb, chunk, crypt, imghdr, msilib, nntplib, nis, ossaudiodev, pipes, smtpd, sndhdr, spwd, sunau, telnetlib, uu, xdrlib

  • bpo-34790: Remove passing coroutine objects to asyncio.wait().

  • bpo-47039: Normalize repr() of asyncio future and task objects.

  • bpo-2604: Fix bug where doctests using globals would fail when run multiple times.

  • bpo-45150: Add hashlib.file_digest() helper for efficient hashing of file object.

  • bpo-34861: Made cumtime the default sorting key for cProfile

  • bpo-45997: Fix asyncio.Semaphore re-aquiring FIFO order.

  • bpo-47022: The asynchat, asyncore and smtpd modules have been deprecated since at least Python 3.6. Their documentation and deprecation warnings and have now been updated to note they will removed in Python 3.12 (PEP 594).

  • bpo-43253: Fix a crash when closing transports where the underlying socket handle is already invalid on the Proactor event loop.

  • bpo-40280: select.select() now passes NULL to select for each empty fdset.

  • bpo-47004: Apply bugfixes from importlib_metadata 4.11.3, including bugfix for EntryPoint.extras, which was returning match objects and not the extras strings.

  • bpo-46998: Allow subclassing of typing.Any. Patch by Shantanu Jain.

  • bpo-46995: Deprecate missing asyncio.Task.set_name() for third-party task implementations, schedule making it mandatory in Python 3.13.

  • bpo-46994: Accept explicit contextvars.Context in asyncio.create_task() and asyncio.loop.create_task().

  • bpo-46981: typing.get_args(typing.Tuple[()]) now returns () instead of ((),).

  • bpo-46968: Add os.sysconf_names['SC_MINSIGSTKSZ'].

  • bpo-46985: Upgrade pip wheel bundled with ensurepip (pip 22.0.4)

  • bpo-46968: faulthandler: On Linux 5.14 and newer, dynamically determine size of signal handler stack size CPython allocates using getauxval(AT_MINSIGSTKSZ). This changes allows for Python extension’s request to Linux kernel to use AMX_TILE instruction set on Sapphire Rapids Xeon processor to succeed, unblocking use of the ISA in frameworks.

  • bpo-46917: The math.nan value is now always available. Patch by Victor Stinner.

  • bpo-46955: Expose asyncio.base_events.Server as asyncio.Server. Patch by Stefan Zabka.

  • bpo-23325: The signal module no longer assumes that SIG_IGN and SIG_DFL are small int singletons.

  • bpo-46932: Update bundled libexpat to 2.4.7

  • bpo-46933: The pwd module is now optional. os.path.expanduser() returns the path when the pwd module is not available.

  • bpo-40059: PEP 680, the tomllib module. Adds support for parsing TOML.

  • bpo-464471: asyncio.timeout() and asyncio.timeout_at() context managers added. Patch by Tin Tvrtković and Andrew Svetlov.

  • bpo-46805: Added raw datagram socket functions for asyncio: sock_sendto(), sock_recvfrom() and sock_recvfrom_into().

  • bpo-46644: No longer require valid typeforms to be callable. This allows typing.Annotated to wrap typing.ParamSpecArgs and dataclasses.InitVar. Patch by Gregory Beauregard.

  • bpo-46581: Brings ParamSpec propagation for GenericAlias in line with Concatenate (and others).

  • bpo-45413: Define posix_venv and nt_venv sysconfig installation schemes to be used for bootstrapping new virtual environments. Add venv sysconfig installation scheme to get the appropriate one of the above. The schemes are identical to the pre-existing posix_prefix and nt install schemes. The venv module now uses the venv scheme to create new virtual environments instead of hardcoding the paths depending only on the platform. Downstream Python distributors customizing the posix_prefix or nt install scheme in a way that is not compatible with the install scheme used in virtual environments are encouraged not to customize the venv schemes. When Python itself runs in a virtual environment, sysconfig.get_default_scheme() and sysconfig.get_preferred_scheme() with key="prefix" returns venv.

  • bpo-43224: Implement support for PEP 646 in typing.py.

  • bpo-43224: Allow unpacking types.GenericAlias objects, e.g. *tuple[int, str].

  • bpo-46557: Warnings captured by the logging module are now logged without a format string to prevent systems that group logs by the msg argument from grouping captured warnings together.

  • bpo-41370: typing.get_type_hints() now supports evaluating strings as forward references in PEP 585 generic aliases.

  • bpo-46607: Add DeprecationWarning to LegacyInterpolation, deprecated in the docstring since Python 3.2. Will be removed in Python 3.13. Use BasicInterpolation or ExtendedInterpolation instead.

  • bpo-26120: pydoc now excludes __future__ imports from the module’s data items.

  • bpo-46480: Add typing.assert_type(). Patch by Jelle Zijlstra.

  • bpo-46421: Fix a unittest issue where if the command was invoked as python -m unittest and the filename(s) began with a dot (.), a ValueError is returned.

  • bpo-46245: Add optional parameter dir_fd in shutil.rmtree().

  • bpo-22859: unittest.TestProgram.usageExit() is marked as deprecated, to be removed in Python 3.13.

  • bpo-46170: Improve the error message when you try to subclass an instance of typing.NewType.

  • bpo-40296: Fix supporting generic aliases in pydoc.

  • bpo-20392: Fix inconsistency with uppercase file extensions in MimeTypes.guess_type(). Patch by Kumar Aditya.

  • bpo-46030: Add LOCAL_CREDS, LOCAL_CREDS_PERSISTENT and SCM_CREDS2 FreeBSD constants to the socket module.

  • bpo-44439: Fix .write() method of a member file in ZipFile, when the input data is an object that supports the buffer protocol, the file length may be wrong.

  • bpo-45171: Fix handling of the stacklevel argument to logging functions in the logging module so that it is consistent across all logging functions and, as advertised, similar to the stacklevel argument used in warn().

  • bpo-24959: Fix bug where unittest sometimes drops frames from tracebacks of exceptions raised in tests.

  • bpo-44859: Raise more accurate and PEP 249 compatible exceptions in sqlite3.

  • bpo-44493: Add missing terminated NUL in sockaddr_un’s length

    This was potentially observable when using non-abstract AF_UNIX datagram sockets to processes written in another programming language.

  • bpo-41930: Add serialize() and deserialize() support to sqlite3. Patch by Erlend E. Aasland.

  • bpo-33178: Added ctypes.BigEndianUnion and ctypes.LittleEndianUnion classes, as originally documented in the library docs but not yet implemented.

  • bpo-43352: Add an Barrier object in synchronization primitives of asyncio Lib in order to be consistent with Barrier from threading and multiprocessing libs*

  • bpo-35859: re module, fix a few bugs about capturing group. In rare cases, capturing group gets an incorrect string. Patch by Ma Lin.

Documentação

Testes

Construção

  • bpo-40280: Add configure option --enable-wasm-dynamic-linking to enable dlopen and MAIN_MODULE / SIDE_MODULE on wasm32-emscripten.

  • bpo-46023: makesetup now detects and skips all duplicated module definitions. The first entry wins.

  • bpo-40280: Add SOABI wasm32-emscripten for Emscripten and wasm32-wasi for WASI on 32bit WASM as well as wasm64 counter parts.

  • bpo-47032: Ensure Windows install builds fail correctly with a non-zero exit code when part of the build fails.

  • bpo-47024: Update OpenSSL to 1.1.1n for macOS installers and all Windows builds.

  • bpo-46996: The tkinter package now requires Tcl/Tk version 8.5.12 or newer.

  • bpo-46973: Add regen-configure make target to regenerate configure script with Christian’s container image quay.io/tiran/cpython_autoconf:269.

  • bpo-46917: Building Python now requires support of IEEE 754 floating-point numbers. Patch by Victor Stinner.

  • bpo-45774: configure now verifies that all SQLite C APIs needed for the sqlite3 extension module are found.

Windows

  • bpo-47194: Update zlib to v1.2.12 to resolve CVE 2018-25032.

  • bpo-47171: Enables installing the py.exe launcher on Windows ARM64.

  • bpo-46566: Upgraded Gerenciador de instalação do Python to support a new -V:company/tag argument for full PEP 514 support and to detect ARM64 installs. The -64 suffix on arguments is deprecated, but still selects any non-32-bit install. Setting PYLAUNCHER_ALLOW_INSTALL and specifying a version that is not installed will attempt to install the requested version from the Microsoft Store.

  • bpo-47086: The installer for Windows now includes documentation as loose HTML files rather than a single compiled .chm file.

  • bpo-46907: Update Windows installer to use SQLite 3.38.1.

  • bpo-44549: Update bzip2 to 1.0.8 in Windows builds to mitigate CVE 2016-3189 and CVE 2019-12900.

  • bpo-46948: Prevent CVE 2022-26488 by ensuring the Add to PATH option in the Windows installer uses the correct path when being repaired.

macOS

  • bpo-46890: Fix a regression in the setting of sys._base_executable in framework builds, and thereby fix a regression in venv virtual environments with such builds.

  • bpo-46907: Update macOS installer to SQLite 3.38.1.

Ferramentas/Demos

  • bpo-40280: Replace Emscripten’s limited shell with Katie Bell’s browser-ui REPL from python-wasm project.

API C

  • bpo-40421: Add PyFrame_GetBuiltins, PyFrame_GetGenerator and PyFrame_GetGlobals C-API functions to access frame object attributes safely from C code.

  • bpo-46850: Move the private _PyFrameEvalFunction type, and private _PyInterpreterState_GetEvalFrameFunc() and _PyInterpreterState_SetEvalFrameFunc() functions to the internal C API. The _PyFrameEvalFunction callback function type now uses the _PyInterpreterFrame type which is part of the internal C API. Patch by Victor Stinner.

  • bpo-46850: Move the private undocumented _PyEval_EvalFrameDefault() function to the internal C API. The function now uses the _PyInterpreterFrame type which is part of the internal C API. Patch by Victor Stinner.

  • bpo-46850: Remove the private undocumented function _PyEval_CallTracing() from the C API. Call the public sys.call_tracing() function instead. Patch by Victor Stinner.

  • bpo-46850: Remove the private undocumented function _PyEval_GetCoroutineOriginTrackingDepth() from the C API. Call the public sys.get_coroutine_origin_tracking_depth() function instead. Patch by Victor Stinner.

  • bpo-46850: Remove the following private undocumented functions from the C API:

    • _PyEval_GetAsyncGenFirstiter()

    • _PyEval_GetAsyncGenFinalizer()

    • _PyEval_SetAsyncGenFirstiter()

    • _PyEval_SetAsyncGenFinalizer()

    Call the public sys.get_asyncgen_hooks() and sys.set_asyncgen_hooks() functions instead. Patch by Victor Stinner.

  • bpo-46987: Remove private functions _PySys_GetObjectId() and _PySys_SetObjectId(). Patch by Donghee Na.

  • bpo-46906: Add new functions to pack and unpack C double (serialize and deserialize): PyFloat_Pack2(), PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack2(), PyFloat_Unpack4() and PyFloat_Unpack8(). Patch by Victor Stinner.

Python 3.11.0 alpha 6

Data de lançamento: 2022-03-07

Núcleo e embutidos

  • bpo-46940: Avoid overriding AttributeError metadata information for nested attribute access calls. Patch by Pablo Galindo.

  • bpo-46927: Include the type’s name in the error message for subscripting non-generic types.

  • bpo-46921: Support vectorcall for super(). Patch by Ken Jin.

  • bpo-46841: Fix incorrect handling of inline cache entries when specializing BINARY_OP.

  • bpo-46841: Use an oparg to simplify the construction of helpful error messages in GET_AWAITABLE.

  • bpo-46903: Make sure that str subclasses can be used as attribute names for instances with virtual dictionaries. Fixes regression in 3.11alpha

  • bpo-46841: Add more detailed specialization failure stats for COMPARE_OP followed by EXTENDED_ARG.

  • bpo-46891: Fix bug introduced during 3.11alpha where subclasses of types.ModuleType with __slots__ were not initialized correctly, resulting in an interpreter crash.

  • bpo-46841: Use inline caching for LOAD_ATTR, LOAD_METHOD, and STORE_ATTR.

  • bpo-46841: Use inline cache for BINARY_SUBSCR.

  • bpo-46841: Use inline caching for COMPARE_OP.

  • bpo-46864: Deprecate PyBytesObject.ob_shash. It will be removed in Python 3.13.

  • bpo-46841: Use inline caching for UNPACK_SEQUENCE.

  • bpo-46845: Reduces dict size by removing hash value from hash table when all inserted keys are Unicode. For example, sys.getsizeof(dict.fromkeys("abcdefg")) becomes 272 bytes from 352 bytes on 64bit platform.

  • bpo-46841: Use inline cache for LOAD_GLOBAL.

  • bpo-46852: Rename the private undocumented float.__set_format__() method to float.__setformat__() to fix a typo introduced in Python 3.7. The method is only used by test_float. Patch by Victor Stinner.

  • bpo-46852: Remove the undocumented private float.__set_format__() method, previously known as float.__setformat__() in Python 3.7. Its docstring said: “You probably don’t want to use this function. It exists mainly to be used in Python’s test suite.” Patch by Victor Stinner.

  • bpo-40116: Fix regression that dict.update(other) may don’t respect iterate order of other when other is key sharing dict.

  • bpo-46712: Share global string identifiers in deep-frozen modules.

  • bpo-46430: Fix memory leak in interned strings of deep-frozen modules.

  • bpo-46841: Store BINARY_OP caches inline using a new CACHE instruction.

  • bpo-45107: Specialize LOAD_METHOD for instances with a dict.

  • bpo-44337: Reduce the memory usage of specialized LOAD_ATTR and STORE_ATTR instructions.

  • bpo-46729: Add number of sub-exceptions to BaseException.__str__().

  • bpo-45885: Don’t un-adapt COMPARE_OP when collecting specialization stats.

  • bpo-46329: Fix specialization stats gathering for PRECALL instructions.

Biblioteca

  • bpo-46794: Bump up the libexpat version into 2.4.6

Núcleo e embutidos

  • bpo-46823: Implement a specialized combined opcode LOAD_FAST__LOAD_ATTR_INSTANCE_VALUE. Patch by Dennis Sweeney.

  • bpo-46820: Fix parsing a numeric literal immediately (without spaces) followed by “not in” keywords, like in 1not in x. Now the parser only emits a warning, not a syntax error.

  • bpo-46329: Move KW_NAMES before PRECALL instruction in call sequence. Change operand of CALL to match PRECALL for easier specialization.

  • bpo-46808: Remove the NEXT_BLOCK macro from compile.c, and make the compiler automatically generate implicit blocks when they are needed.

  • bpo-46329: Add PUSH_NULL instruction. This is used as a prefix when evaluating a callable, so that the stack has the same shape for methods and other calls. PRECALL_FUNCTION and PRECALL_METHOD are merged into a single PRECALL instruction.

    There is no change in semantics.

  • bpo-46762: Fix an assert failure in debug builds when a ‘<’, ‘>’, or ‘=’ is the last character in an f-string that’s missing a closing right brace.

  • bpo-46730: Message of AttributeError caused by getting, setting or deleting a property without the corresponding function now mentions that the attribute is in fact a property and also specifies type of the class that it belongs to.

  • bpo-46724: Make sure that all backwards jumps use the JUMP_ABSOLUTE instruction, rather than JUMP_FORWARD with an argument of (2**32)+offset.

  • bpo-46732: Correct the docstring for the __bool__() method. Patch by Jelle Zijlstra.

  • bpo-46072: Add more detailed specialization failure statistics for BINARY_OP.

  • bpo-46707: Avoid potential exponential backtracking when producing some syntax errors involving lots of brackets. Patch by Pablo Galindo.

Biblioteca

  • bpo-46323: ctypes now allocates memory on the stack instead of on the heap to pass arguments while calling a Python callback function. Patch by Donghee Na.

Núcleo e embutidos

  • bpo-45923: Add a quickened form of RESUME that skips quickening checks.

  • bpo-46702: Specialize UNPACK_SEQUENCE for tuple and list unpackings.

  • bpo-46072: Opcode pair stats are now gathered with --enable-pystats. Defining DYNAMIC_EXECUTION_PROFILE or DXPAIRS no longer has any effect.

  • bpo-46675: Allow more than 16 items in a split dict before it is combined. The limit is now 254.

Biblioteca

Núcleo e embutidos

  • bpo-46615: When iterating over sets internally in setobject.c, acquire strong references to the resulting items from the set. This prevents crashes in corner-cases of various set operations where the set gets mutated.

  • bpo-45828: The bytecode compiler now attempts to apply runtime stack manipulations at compile-time (whenever it is feasible to do so).

  • bpo-30496: Fixed a minor portability issue in the implementation of PyLong_FromLong(), and added a fast path for single-digit integers to PyLong_FromLongLong().

Biblioteca

Documentação

  • bpo-42238: Doc/tools/rstlint.py has moved to its own repository and is now packaged on PyPI as sphinx-lint.

Testes

  • bpo-46913: Fix test_faulthandler.test_sigfpe() if Python is built with undefined behavior sanitizer (UBSAN): disable UBSAN on the faulthandler_sigfpe() function. Patch by Victor Stinner.

  • bpo-46760: Remove bytecode offsets from expected values in test.test_dis module. Reduces the obstacles to modifying the VM or compiler.

  • bpo-46708: Prevent default asyncio event loop policy modification warning after test_asyncio execution.

  • bpo-46678: The function make_legacy_pyc in Lib/test/support/import_helper.py no longer fails when PYTHONPYCACHEPREFIX is set to a directory on a different device from where tempfiles are stored.

  • bpo-46623: Skip test_pair() and test_speech128() of test_zlib on s390x since they fail if zlib uses the s390x hardware accelerator. Patch by Victor Stinner.

Construção

  • bpo-46860: Respect --with-suffix when building on case-insensitive file systems.

  • bpo-46656: Building Python now requires a C11 compiler. Optional C11 features are not required. Patch by Victor Stinner.

  • bpo-46656: Building Python now requires support for floating-point Not-a-Number (NaN): remove the Py_NO_NAN macro. Patch by Victor Stinner.

  • bpo-46640: Building Python now requires a C99 <math.h> header file providing a NAN constant, or the __builtin_nan() built-in function. Patch by Victor Stinner.

  • bpo-46608: Exclude marshalled-frozen data if deep-freezing to save 300 KB disk space. This includes adding a new is_package field to _frozen. Patch by Kumar Aditya.

  • bpo-40280: Fix wasm32-emscripten test failures and platform issues. - Disable syscalls that are not supported or don’t work, e.g. wait, getrusage, prlimit, mkfifo, mknod, setres[gu]id, setgroups. - Use fd_count to count open fds. - Add more checks for subprocess and fork. - Add workarounds for missing _multiprocessing and failing socket.accept(). - Enable bzip2. - Disable large file support. - Disable signal.alarm.

  • bpo-46430: Intern strings in deep-frozen modules. Patch by Kumar Aditya.

Windows

  • bpo-46744: The default all users install directory for ARM64 is now under the native Program Files folder, rather than Program Files (Arm) which is intended for ARM (32-bit) files.

  • bpo-46567: Adds Tcl and Tk support for Windows ARM64. This also adds IDLE to the installation.

  • bpo-46638: Ensures registry virtualization is consistently disabled. For 3.10 and earlier, it remains enabled (some registry writes are protected), while for 3.11 and later it is disabled (registry modifications affect all applications).

IDLE

  • bpo-46630: Make query dialogs on Windows start with a cursor in the entry box.

  • bpo-45447: Apply IDLE syntax highlighting to .pyi files. Patch by Alex Waygood and Terry Jan Reedy.

API C

  • bpo-46748: Python’s public headers no longer import <stdbool.h>, leaving code that embeds/extends Python free to define bool, true and false.

  • bpo-46836: Move the PyFrameObject type definition (struct _frame) to the internal C API pycore_frame.h header file. Patch by Victor Stinner.

  • bpo-45459: Rename Include/buffer.h header file to Include/pybuffer.h to avoid conflicts with projects having an existing buffer.h header file. Patch by Victor Stinner.

  • bpo-45412: Remove the HAVE_PY_SET_53BIT_PRECISION macro (moved to the internal C API). Patch by Victor Stinner.

  • bpo-46613: Added function PyType_GetModuleByDef(), which allows access to module state when a method’s defining class is not available.

Python 3.11.0 alpha 5

Data de lançamento: 2022-02-03

Núcleo e embutidos

  • bpo-45773: Remove two invalid “peephole” optimizations from the bytecode compiler.

  • bpo-46564: Do not create frame objects when creating super object. Patch by Kumar Aditya.

  • bpo-45885: Added more fined-grained specialization failure stats regarding the COMPARE_OP bytecode.

  • bpo-44977: The delegation of int() to __trunc__() is now deprecated. Calling int(a) when type(a) implements __trunc__() but not __int__() or __index__() now raises a DeprecationWarning.

  • bpo-46458: Reorder code emitted by the compiler for a try-except block so that the else block’s code immediately follows the try body (without a jump). This is more optimal for the happy path.

  • bpo-46527: Allow passing iterable as a keyword argument to enumerate() again. Patch by Jelle Zijlstra.

  • bpo-46528: Replace several stack manipulation instructions (DUP_TOP, DUP_TOP_TWO, ROT_TWO, ROT_THREE, ROT_FOUR, and ROT_N) with new COPY and SWAP instructions.

  • bpo-46329: Use two or three bytecodes to implement most calls.

    Calls without named arguments are implemented as a sequence of two instructions: PRECALL; CALL. Calls with named arguments are implemented as a sequence of three instructions: PRECALL; KW_NAMES; CALL. There are two different PRECALL instructions: PRECALL_FUNTION and PRECALL_METHOD. The latter pairs with LOAD_METHOD.

    This partition into pre-call and call allows better specialization, and thus better performance ultimately.

    There is no change in semantics.

  • bpo-46503: Fix an assert when parsing some invalid N escape sequences in f-strings.

  • bpo-46431: Improve error message on invalid calls to BaseExceptionGroup.__new__().

  • bpo-46476: Fix memory leak in code objects generated by deepfreeze. Patch by Kumar Aditya.

  • bpo-46481: Speed up calls to weakref.ref.__call__() by using the PEP 590 vectorcall calling convention. Patch by Donghee Na.

  • bpo-46417: Fix a race condition on setting a type __bases__ attribute: the internal function add_subclass() now gets the PyTypeObject.tp_subclasses member after calling PyWeakref_NewRef() which can trigger a garbage collection which can indirectly modify PyTypeObject.tp_subclasses. Patch by Victor Stinner.

  • bpo-46417: python -X showrefcount now shows the total reference count after clearing and destroyed the main Python interpreter. Previously, it was shown before. Patch by Victor Stinner.

  • bpo-43683: Add ASYNC_GEN_WRAP opcode to wrap the value to be yielded in async generators. Removes the need to special case async generators in the YIELD_VALUE instruction.

  • bpo-46407: Optimize some modulo operations in Objects/longobject.c. Patch by Jeremiah Vivian.

  • bpo-46409: Add new RETURN_GENERATOR bytecode to make generators. Simplifies calling Python functions in the VM, as they no longer any need to special case generator functions.

    Also add JUMP_NO_INTERRUPT bytecode that acts like JUMP_ABSOLUTE, but does not check for interrupts.

  • bpo-46406: The integer division // implementation has been optimized to better let the compiler understand its constraints. It can be 20% faster on the amd64 platform when dividing an int by a value smaller than 2**30.

Biblioteca

  • bpo-46383: Fix invalid signature of _zoneinfo’s module_free function to resolve a crash on wasm32-emscripten platform.

Núcleo e embutidos

  • bpo-46361: Ensure that “small” integers created by int.from_bytes() and decimal.Decimal are properly cached.

  • bpo-46161: Fix the class building error when the arguments are constants and CALL_FUNCTION_EX is used.

  • bpo-46028: Fixes calculation of sys._base_executable when inside a virtual environment that uses symlinks with different binary names than the base environment provides.

  • bpo-46091: Correctly calculate indentation levels for lines with whitespace character that are ended by line continuation characters. Patch by Pablo Galindo

Biblioteca

  • bpo-30512: Add CAN Socket support for NetBSD.

Construção

  • bpo-46045: Do not use POSIX semaphores on NetBSD

Núcleo e embutidos

Biblioteca

Documentação

  • bpo-46463: Fixes escape4chm.py script used when building the CHM documentation file

Testes

  • bpo-43478: Mocks can no longer be provided as the specs for other Mocks. As a result, an already-mocked object cannot be passed to mock.Mock(). This can uncover bugs in tests since these Mock-derived Mocks will always pass certain tests (e.g. isinstance) and builtin assert functions (e.g. assert_called_once_with) will unconditionally pass.

  • bpo-46616: Ensures test_importlib.test_windows cleans up registry keys after completion.

  • bpo-44359: test_ftplib now silently ignores socket errors to prevent logging unhandled threading exceptions. Patch by Victor Stinner.

  • bpo-46600: Fix test_gdb.test_pycfunction() for Python built with clang -Og. Tolerate inlined functions in the gdb traceback. Patch by Victor Stinner.

  • bpo-46542: Fix a Python crash in test_lib2to3 when using Python built in debug mode: limit the recursion limit. Patch by Victor Stinner.

  • bpo-46576: test_peg_generator now disables compiler optimization when testing compilation of its own C extensions to significantly speed up the testing on non-debug builds of CPython.

  • bpo-46542: Fix test_json tests checking for RecursionError: modify these tests to use support.infinite_recursion(). Patch by Victor Stinner.

  • bpo-13886: Skip test_builtin PTY tests on non-ASCII characters if the readline module is loaded. The readline module changes input() behavior, but test_builtin is not intended to test the readline module. Patch by Victor Stinner.

  • bpo-40280: Add test.support.requires_fork() decorators to mark tests that require a working os.fork().

  • bpo-40280: Add test.support.requires_subprocess() decorator to mark tests which require working subprocess module or os.spawn*. The wasm32-emscripten platform has no support for processes.

  • bpo-46126: Disable ‘descriptions’ when running tests internally.

Construção

  • bpo-46602: Tidied up configure.ac so that conftest.c is truncated rather than appended. This assists in the case where the ‘rm’ of conftest.c fails to happen between tests. Downstream issues such as a clobbered SOABI can result.

  • bpo-46600: Fix the test checking if the C compiler supports -Og option in the ./configure script to also use -Og on clang which supports it. Patch by Victor Stinner.

  • bpo-38472: Fix GCC detection in setup.py when cross-compiling. The C compiler is now run with LC_ALL=C. Previously, the detection failed with a German locale.

  • bpo-46513: configure no longer uses AC_C_CHAR_UNSIGNED macro and pyconfig.h no longer defines reserved symbol __CHAR_UNSIGNED__.

  • bpo-46471: Use global singletons for single byte bytes objects in deepfreeze.

  • bpo-46443: Deepfreeze now uses cached small integers as it saves some space for common small integers.

  • bpo-46429: Merge all deep-frozen files into one for space savings. Patch by Kumar Aditya.

  • bpo-45569: The build now defaults to using 30-bit digits for Python integers. Previously either 15-bit or 30-bit digits would be selected, depending on the platform. 15-bit digits may still be selected using the --enable-big-digits=15 option to the configure script, or by defining PYLONG_BITS_IN_DIGIT in pyconfig.h.

  • bpo-45925: Update Windows installer to use SQLite 3.37.2.

  • bpo-43112: Detect musl libc as a separate SOABI (tagged as linux-musl).

Windows

  • bpo-33125: The traditional EXE/MSI based installer for Windows is now available for ARM64

  • bpo-46362: os.path.abspath(“C:CON”) is now fixed to return “\.CON”, not the same path. The regression was true of all legacy DOS devices such as COM1, LPT1, or NUL.

  • bpo-44934: The installer now offers a command-line only option to add the installation directory to the end of PATH instead of at the start.

macOS

  • bpo-45925: Update macOS installer to SQLite 3.37.2.

IDLE

  • bpo-45296: Clarify close, quit, and exit in IDLE. In the File menu, ‘Close’ and ‘Exit’ are now ‘Close Window’ (the current one) and ‘Exit’ is now ‘Exit IDLE’ (by closing all windows). In Shell, ‘quit()’ and ‘exit()’ mean ‘close Shell’. If there are no other windows, this also exits IDLE.

API C

  • bpo-40170: Remove the PyHeapType_GET_MEMBERS() macro. It was exposed in the public C API by mistake, it must only be used by Python internally. Use the PyTypeObject.tp_members member instead. Patch by Victor Stinner.

  • bpo-40170: Move _Py_GetAllocatedBlocks() and _PyObject_DebugMallocStats() private functions to the internal C API. Patch by Victor Stinner.

  • bpo-46433: The internal function _PyType_GetModuleByDef now correctly handles inheritance patterns involving static types.

  • bpo-45459: Py_buffer and various Py_buffer related functions are now part of the limited API and stable ABI.

  • bpo-14916: Fixed bug in the tokenizer that prevented PyRun_InteractiveOne from parsing from the provided FD.

Python 3.11.0 alpha 4

Data de lançamento: 2022-01-13

Núcleo e embutidos

  • bpo-46070: Py_EndInterpreter() now explicitly untracks all objects currently tracked by the GC. Previously, if an object was used later by another interpreter, calling PyObject_GC_UnTrack() on the object crashed if the previous or the next object of the PyGC_Head structure became a dangling pointer. Patch by Victor Stinner.

  • bpo-46347: Fix memory leak in PyEval_EvalCodeEx.

  • bpo-46339: Fix a crash in the parser when retrieving the error text for multi-line f-strings expressions that do not start in the first line of the string. Patch by Pablo Galindo

  • bpo-46331: Do not set line number of instruction storing doc-string. Fixes regression introduced in 3.11 alpha.

  • bpo-46314: Remove spurious “call” event when creating a lambda function that was accidentally introduced in 3.11a4.

  • bpo-46289: ASDL declaration of FormattedValue has changed to reflect conversion field is not optional.

  • bpo-46297: Fixed an interpreter crash on bootup with multiple PythonPaths set in the Windows registry. Patch by Derzsi Dániel.

  • bpo-46237: Fix the line number of tokenizer errors inside f-strings. Patch by Pablo Galindo.

  • bpo-46263: We always expect the “use_frozen_modules” config to be set, now that getpath.c was rewritten in pure Python and the logic improved.

  • bpo-46006: Fix a regression when a type method like __init__() is modified in a subinterpreter. Fix a regression in _PyUnicode_EqualToASCIIId() and type update_slot(). Revert the change which made the Unicode dictionary of interned strings compatible with subinterpreters: the internal interned dictionary is shared again by all interpreters. Patch by Victor Stinner.

  • bpo-45923: Add RESUME opcode. This is a logical no-op. It is emitted by the compiler anywhere a Python function can be entered. It is used by the interpreter to perform tracing and optimizer checks.

Biblioteca

  • bpo-46208: Fix the regression of os.path.normpath(“A/../../B”) not returning expected “../B” but “B”.

Núcleo e embutidos

  • bpo-46240: Correct the error message for unclosed parentheses when the tokenizer doesn’t reach the end of the source when the error is reported. Patch by Pablo Galindo

  • bpo-46009: Remove the GEN_START opcode.

  • bpo-46235: Certain sequence multiplication operations like [0] * 1_000 are now faster due to reference-counting optimizations. Patch by Dennis Sweeney.

  • bpo-46221: PREP_RERAISE_STAR no longer pushes lasti to the stack.

  • bpo-46202: Remove POP_EXCEPT_AND_RERAISE and replace it by an equivalent sequence of other opcodes.

Biblioteca

  • bpo-46085: Fix iterator cache mechanism of OrderedDict.

Núcleo e embutidos

  • bpo-46055: Speed up shifting operation involving integers less than PyLong_BASE. Patch by Xinhang Xu.

  • bpo-46110: Add a maximum recursion check to the PEG parser to avoid stack overflow. Patch by Pablo Galindo

  • bpo-46107: Fix bug where ExceptionGroup.split() and ExceptionGroup.subgroup() did not copy the exception group’s __note__ field to the parts.

  • bpo-45711: The interpreter state’s representation of handled exceptions (a.k.a exc_info, or _PyErr_StackItem) now has only the exc_value field, exc_type and exc_traceback have been removed as their values can be derived from exc_value.

  • bpo-44525: Replace the four call bytecode instructions which one pre-call instruction and two call instructions.

    Removes CALL_FUNCTION, CALL_FUNCTION_KW, CALL_METHOD and CALL_METHOD_KW.

    Adds CALL_NO_KW and CALL_KW call instructions, and PRECALL_METHOD prefix for pairing with LOAD_METHOD.

  • bpo-46039: Remove the YIELD_FROM instruction and replace it with the SEND instruction which performs the same operation, but without the loop.

  • bpo-45635: The code called from _PyErr_Display() was refactored to improve error handling. It now exits immediately upon an unrecoverable error.

  • bpo-46054: Fix parser error when parsing non-utf8 characters in source files. Patch by Pablo Galindo.

  • bpo-46042: Improve the location of the caret in SyntaxError exceptions emitted by the symbol table. Patch by Pablo Galindo.

  • bpo-46049: Ensure ._pth files work as intended on platforms other than Windows.

  • bpo-46048: Fixes parsing of ._pth files on startup so that single-character paths are correctly read.

  • bpo-37971: Fix a bug where the line numbers given in a traceback when a decorator application raised an exception were wrong.

  • bpo-46031: Add POP_JUMP_IF_NOT_NONE and POP_JUMP_IF_NONE opcodes to speed up conditional jumps.

  • bpo-45654: Deepfreeze runpy, patch by Kumar Aditya.

  • bpo-46025: Fix a crash in the atexit module involving functions that unregister themselves before raising exceptions. Patch by Pablo Galindo.

Biblioteca

  • bpo-46000: Improve compatibility of the curses module with NetBSD curses.

Núcleo e embutidos

  • bpo-44525: Specialize the CALL_FUNCTION instruction for calls to builtin types with a single argument. Speeds up range(x), list(x), and specifically type(obj).

  • bpo-42918: Fix bug where the built-in compile() function did not always raise a SyntaxError when passed multiple statements in ‘single’ mode. Patch by Weipeng Hong.

  • bpo-45953: The main interpreter in _PyRuntimeState.interpreters is now statically allocated (as part of _PyRuntime). Likewise for the initial thread state of each interpreter. This means less allocation during runtime init, as well as better memory locality for these key state objects.

  • bpo-45292: Complete the PEP 654 implementation: add except*.

  • bpo-43413: Revert changes in set.__init__. Subclass of set needs to define a __init__() method if it defines a __new__() method with additional keyword parameters.

  • bpo-43931: Added the Py_Version constant which bears the same value as PY_VERSION_HEX. Patch by Gabriele N. Tornetta.

Biblioteca

  • bpo-46342: The @typing.final decorator now sets the __final__ attribute on the decorated object to allow runtime introspection. Patch by Jelle Zijlstra.

  • bpo-46328: Added the sys.exception() method which returns the active exception instance.

  • bpo-46307: Add string.Template.is_valid() and string.Template.get_identifiers() methods.

  • bpo-46306: Assume that types.CodeType always has types.CodeType.co_firstlineno in doctest.

  • bpo-40479: Fix hashlib usedforsecurity option to work correctly with OpenSSL 3.0.0 in FIPS mode.

  • bpo-46070: Fix possible segfault when importing the asyncio module from different sub-interpreters in parallel. Patch by Erlend E. Aasland.

  • bpo-46244: Removed __slots__ from typing.ParamSpec and typing.TypeVar. They served no purpose. Patch by Arie Bovenberg.

  • bpo-46278: Reflect context argument in AbstractEventLoop.call_*() methods. Loop implementations already support it.

  • bpo-46269: Remove special-casing of __new__ in enum.Enum.__dir__().

  • bpo-46266: Improve day constants in calendar.

    Now all constants (MONDAY … SUNDAY) are documented, tested, and added to __all__.

  • bpo-46257: Optimized the mean, variance, and stdev functions in the statistics module. If the input is an iterator, it is consumed in a single pass rather than eating memory by conversion to a list. The single pass algorithm is about twice as fast as the previous two pass code.

  • bpo-41011: Added two new variables to pyvenv.cfg which is generated by venv module: executable for the executable and command for the command line used to create the environment.

  • bpo-46239: Improve error message when importing asyncio.windows_events on non-Windows.

  • bpo-46238: Reuse _winapi constants in asyncio.windows_events.

  • bpo-46222: Adding SF_NOCACHE sendfile constant for FreeBSD for the posixmodule.

  • bpo-37295: Add fast path for 0 <= k <= n <= 67 for math.comb().

  • bpo-46176: Adding the MAP_STACK constant for the mmap module.

  • bpo-43424: Deprecate webbrowser.MacOSXOSAScript._name and use name instead.

  • bpo-45321: Added missing error codes to module xml.parsers.expat.errors.

  • bpo-46125: Refactor tests to test traversable API directly. Includes changes from importlib 5.4.0.

  • bpo-46118: Moved importlib.resources and its related functionality to a package.

  • bpo-37578: Add include_hidden parameter to glob() and iglob() to match hidden files and directories when using special characters like *, **, ? and [].

  • bpo-20369: concurrent.futures.wait() no longer blocks forever when given duplicate Futures. Patch by Kumar Aditya.

  • bpo-46105: Honor spec when generating requirement specs with urls and extras (importlib_metadata 4.8.3).

  • bpo-44893: EntryPoint objects are no longer tuples. Recommended means to access is by attribute (‘.name’, ‘.group’) or accessor (‘.load()’). Access by index is deprecated and will raise deprecation warning.

  • bpo-22815: Print unexpected successes together with failures and errors in summary in unittest.TextTestResult.

  • bpo-22047: Calling add_argument_group() on an argument group is deprecated. Calling add_argument_group() or add_mutually_exclusive_group() on a mutually exclusive group is deprecated.

    These features were never supported and do not always work correctly. The functions exist on the API by accident through inheritance and will be removed in the future.

  • bpo-26952: argparse raises ValueError with clear message when trying to render usage for an empty mutually exclusive group. Previously it raised a cryptic IndexError.

  • bpo-45615: Functions in the traceback module raise TypeError rather than AttributeError when an exception argument is not of type BaseException.

  • bpo-16594: Add allow allow_reuse_port flag in socketserver.

  • bpo-27718: Fix help for the signal module. Some functions (e.g. signal() and getsignal()) were omitted.

  • bpo-46032: The registry() method of functools.singledispatch() functions checks now the first argument or the first parameter annotation and raises a TypeError if it is not supported. Previously unsupported “types” were ignored (e.g. typing.List[int]) or caused an error at calling time (e.g. list[int]).

  • bpo-46014: Add ability to use typing.Union and types.UnionType as dispatch argument to functools.singledispatch. Patch provided by Yurii Karabas.

  • bpo-27062: Add __all__ to inspect, patch by Kumar Aditya.

  • bpo-46018: Ensure that math.expm1() does not raise on underflow.

  • bpo-46016: Adding F_DUP2FD and F_DUP2FD_CLOEXEC constants from FreeBSD into the fcntl module.

  • bpo-45755: typing generic aliases now reveal the class attributes of the original generic class when passed to dir(). This was the behavior up to Python 3.6, but was changed in 3.7-3.9.

  • bpo-45874: The empty query string, consisting of no query arguments, is now handled correctly in urllib.parse.parse_qsl. This caused problems before when strict parsing was enabled.

  • bpo-44674: Change how dataclasses disallows mutable default values. It used to use a list of known types (list, dict, set). Now it disallows unhashable objects to be defaults. It’s using unhashability as a proxy for mutability. Patch by Eric V. Smith, idea by Raymond Hettinger.

  • bpo-23882: Remove namespace package (PEP 420) support from unittest discovery. It was introduced in Python 3.4 but has been broken since Python 3.7.

  • bpo-25066: Added a __repr__() method to multiprocessing.Event objects, patch by Kumar Aditya.

  • bpo-45643: Added signal.SIGSTKFLT on platforms where this signal is defined.

  • bpo-44092: Fetch across rollback no longer raises InterfaceError. Instead we leave it to the SQLite library to handle these cases. Patch by Erlend E. Aasland.

  • bpo-42413: Replace concurrent.futures.TimeoutError and asyncio.TimeoutError with builtin TimeoutError, keep these names as deprecated aliases.

Documentação

Testes

  • bpo-46296: Add a test case for enum with _use_args_ == True and _member_type_ == object.

  • bpo-46205: Fix hang in runtest_mp due to race condition

  • bpo-46263: Fix test_capi on FreeBSD 14-dev: instruct jemalloc to not fill freed memory with junk byte.

  • bpo-46262: Cover ValueError path in tests for enum.Flag._missing_().

  • bpo-46150: Now fakename in test_pathlib.PosixPathTest.test_expanduser is checked to be non-existent.

  • bpo-46129: Rewrite asyncio.locks tests with unittest.IsolatedAsyncioTestCase usage.

  • bpo-23819: Fixed asyncio tests in python optimized mode. Patch by Kumar Aditya.

  • bpo-46114: Fix test case for OpenSSL 3.0.1 version. OpenSSL 3.0 uses 0xMNN00PP0L.

Construção

  • bpo-44133: When Python is configured with --without-static-libpython, the Python static library (libpython.a) is no longer built. Patch by Victor Stinner.

  • bpo-44133: When Python is built without --enable-shared, the python program is now linked to object files, rather than being linked to the Python static library (libpython.a), to make sure that all symbols are exported. Previously, the linker omitted some symbols like the Py_FrozenMain() function. Patch by Victor Stinner.

  • bpo-40280: The configure script has a new option --with-emscripten-target to select browser or node as Emscripten build target.

  • bpo-46315: Added and fixed #ifdef HAVE_FEATURE checks for functionality that is not available on WASI platform.

  • bpo-45723: Fixed a regression in configure check for select.epoll().

  • bpo-46263: configure no longer sets MULTIARCH on FreeBSD platforms.

  • bpo-46106: Updated OpenSSL to 1.1.1m in Windows builds, macOS installer builds, and CI. Patch by Kumar Aditya.

  • bpo-46088: Automatically detect or install bootstrap Python runtime when building from Visual Studio.

  • bpo-46072: Add a –with-pystats configure option to turn on internal statistics gathering.

  • bpo-40280: Um novo diretório Tools/wasm contém auxiliares relacionados a WebAssembly, como config.site próprio para wasm32-emscripten, arquivos do gerador wasm para empacotar a stdlib e um README.

  • bpo-46023: makesetup no longer builds extensions that have been marked as disabled. This allows users to disable modules in Modules/Setup.local.

  • bpo-45949: Use pure Python freeze_module for all but importlib bootstrap files. --with-freeze-module configure option is no longer needed for cross builds.

Windows

  • bpo-46217: Removed parameter that is unsupported on Windows 8.1 and early Windows 10 and may have caused build or runtime failures.

macOS

  • bpo-40477: The Python Launcher app for macOS now properly launches scripts and, if necessary, the Terminal app when running on recent macOS releases.

API C

Python 3.11.0 alpha 3

Data de lançamento: 2021-12-08

Núcleo e embutidos

  • bpo-46009: Restore behavior from 3.9 and earlier when sending non-None to newly started generator. In 3.9 this did not affect the state of the generator. In 3.10.0 and 3.10.1 gen_func().send(0) is equivalent to gen_func().throw(TypeError(...) which exhausts the generator. In 3.10.2 onward, the behavior has been reverted to that of 3.9.

  • bpo-46004: Fix the SyntaxError location for errors involving for loops with invalid targets. Patch by Pablo Galindo

  • bpo-45711: _PyErr_ChainStackItem() no longer normalizes exc_info (including setting the traceback on the exception instance) because exc_info is always normalized.

  • bpo-45607: The __note__ field was added to BaseException. It is None by default but can be set to a string which is added to the exception’s traceback.

  • bpo-45947: Place pointers to dict and values immediately before GC header. This reduces number of dependent memory loads to access either dict or values from 3 to 1.

  • bpo-45915: is_valid_fd now uses faster fcntl(fd, F_GETFD) on Linux, macOS, and Windows.

  • bpo-44530: Reverts a change to the code.__new__ audit event from an earlier prerelease.

  • bpo-42268: Fail the configure step if the selected compiler doesn’t support memory sanitizer. Patch by Pablo Galindo

  • bpo-45711: The three values of exc_info are now always consistent with each other. In particular, the type and traceback fields are now derived from the exception instance. This impacts the return values of sys.exc_info() and PyErr_GetExcInfo() if the exception instance is modified while the exception is handled, as well as PyErr_SetExcInfo(), which now ignores the type and traceback arguments provided to it.

  • bpo-45727: Refine the custom syntax error that suggests that a comma may be missing to trigger only when the expressions are detected between parentheses or brackets. Patch by Pablo Galindo

  • bpo-45885: Specialized the COMPARE_OP opcode using the PEP 659 machinery.

  • bpo-45786: Allocate space for the interpreter frame in the frame object, to avoid an additional allocation when the frame object outlives the frame activation.

Biblioteca

Núcleo e embutidos

  • bpo-45813: Fix crash when calling coro.cr_frame.clear() after coroutine has been freed.

  • bpo-45811: Improve the tokenizer errors when encountering invisible control characters in the parser. Patch by Pablo Galindo

  • bpo-45848: Allow the parser to obtain error lines directly from encoded files. Patch by Pablo Galindo

  • bpo-45709: Restore behavior from 3.10 when tracing an exception raised within a with statement.

  • bpo-44525: Adds new COPY_FREE_VARS opcode, to make copying of free variables from function to frame explicit. Helps optimization of calls to Python function.

  • bpo-45829: Specialize BINARY_SUBSCR for classes with a __getitem__ method implemented in Python

  • bpo-45826: Fixed a crash when calling .with_traceback(None) on NameError. This occurs internally in unittest.TestCase.assertRaises().

  • bpo-45822: Fixed a bug in the parser that was causing it to not respect PEP 263 coding cookies when no flags are provided. Patch by Pablo Galindo

  • bpo-45820: Fix a segfault when the parser fails without reading any input. Patch by Pablo Galindo

  • bpo-45636: Simplify the implementation of BINARY_OP by indexing into an array of function pointers (rather than switching on the oparg).

  • bpo-42540: Fix crash when os.fork() is called with an active non-default memory allocator.

  • bpo-45738: Fix computation of error location for invalid continuation characters in the parser. Patch by Pablo Galindo.

  • bpo-45636: Remove an existing “fast path” for old-style string formatting, since it no longer appears to have any measurable impact.

  • bpo-45753: Make recursion checks a bit more efficient by tracking amount of calls left before overflow.

  • bpo-45773: Fix a compiler hang when attempting to optimize certain jump patterns.

  • bpo-45764: The parser now gives a better error message when leaving out the opening parenthesis ( after a def-statement:

    >>> def f:
      File "<stdin>", line 1
        def f:
             ^
    SyntaxError: expected '('
    
  • bpo-45609: Specialized the STORE_SUBSCR opcode using the PEP 659 machinery.

  • bpo-45636: Replace all numeric BINARY_* and INPLACE_* instructions with a single BINARY_OP implementation.

  • bpo-45582: Path calculation (known as getpath) has been reimplemented as a frozen Python module. This should have no visible impact, but may affect calculation of all paths referenced in sys and sysconfig.

  • bpo-45450: Improve the syntax error message for parenthesized arguments. Patch by Pablo Galindo.

Biblioteca

  • bpo-27946: Fix possible crash when getting an attribute of xml.etree.ElementTree.Element simultaneously with replacing the attrib dict.

  • bpo-45711: Make asyncio normalize exceptions as soon as they are captured with PyErr_Fetch(), and before they are stored as an exc_info triplet. This brings asyncio in line with the rest of the codebase, where an exc_info triplet is always normalized.

  • bpo-23819: Replaced asserts with exceptions in asyncio, patch by Kumar Aditya.

  • bpo-13236: unittest.TextTestResult and unittest.TextTestRunner flush now the output stream more often.

  • bpo-45917: Added math.exp2():, which returns 2 raised to the power of x.

  • bpo-37658: Fix issue when on certain conditions asyncio.wait_for() may allow a coroutine to complete successfully, but fail to return the result, potentially causing memory leaks or other issues.

  • bpo-45876: Improve the accuracy of stdev() and pstdev() in the statistics module. When the inputs are floats or fractions, the output is a correctly rounded float

  • bpo-44649: Handle dataclass(slots=True) with a field that has default a default value, but for which init=False.

  • bpo-45803: Added missing kw_only parameter to dataclasses.make_dataclass().

  • bpo-45837: The turtle.RawTurtle.settiltangle() is deprecated since Python 3.1, it now emits a deprecation warning and will be removed in Python 3.13.

    Use turtle.RawTurtle.tiltangle() instead.

    turtle.RawTurtle.tiltangle() was earlier incorrectly marked as deprecated, its docstring has been corrected.

    Patch por Hugo van Kemenade.

  • bpo-45831: faulthandler can now write ASCII-only strings (like filenames and function names) with a single write() syscall when dumping a traceback. It reduces the risk of getting an unreadable dump when two threads or two processes dump a traceback to the same file (like stderr) at the same time. Patch by Victor Stinner.

  • bpo-45828: sqlite C callbacks now use unraisable exceptions if callback tracebacks are enabled. Patch by Erlend E. Aasland.

  • bpo-41735: Fix thread lock in zlib.Decompress.flush() method before PyObject_GetBuffer.

  • bpo-45235: Reverted an argparse bugfix that caused regression in the handling of default arguments for subparsers. This prevented leaf level arguments from taking precedence over root level arguments.

  • bpo-45754: Fix a regression in Python 3.11a1 and 3.11a2 where sqlite3 incorrectly would use SQLITE_LIMIT_LENGTH when checking SQL statement lengths. Now, SQLITE_LIMIT_SQL_LENGTH is used. Patch by Erlend E. Aasland.

  • bpo-45766: Added proportional option to statistics.linear_regression().

  • bpo-45765: In importlib.metadata, fix distribution discovery for an empty path.

  • bpo-45757: Fix bug where dis produced an incorrect oparg when EXTENDED_ARG is followed by an opcode that does not use its argument.

  • bpo-45644: In-place JSON file formatting using python3 -m json.tool infile infile now works correctly, previously it left the file empty. Patch by Chris Wesseling.

  • bpo-45703: When a namespace package is imported before another module from the same namespace is created/installed in a different sys.path location while the program is running, calling the importlib.invalidate_caches() function will now also guarantee the new module is noticed.

  • bpo-45535: Improve output of dir() with Enums.

  • bpo-45664: Fix types.resolve_bases() and types.new_class() for types.GenericAlias instance as a base.

  • bpo-45663: Fix dataclasses.is_dataclass() for dataclasses which are subclasses of types.GenericAlias.

  • bpo-45662: Fix the repr of dataclasses.InitVar with a type alias to the built-in class, e.g. InitVar[list[int]].

  • bpo-43137: Launch GNOME web browsers via gio tool instead of obsolete gvfs-open

  • bpo-45429: On Windows, time.sleep() now uses a waitable timer which supports high-resolution timers. Patch by Donghee Na and Eryk Sun.

  • bpo-37295: Optimize math.comb() and math.perm().

  • bpo-45514: Deprecated legacy functions in importlib.resources.

  • bpo-45507: Add tests for truncated/missing trailers in gzip.decompress implementation.

  • bpo-45359: Implement PEP 585 for graphlib.TopologicalSorter.

  • bpo-44733: Add max_tasks_per_child to concurrent.futures.ProcessPoolExecutor. This allows users to specify the maximum number of tasks a single process should execute before the process needs to be restarted.

  • bpo-28806: Improve netrc library. netrc file no longer needs to contain all tokens. And if the login name is anonymous, security check is no longer need.

  • bpo-43498: Avoid a possible “RuntimeError: dictionary changed size during iteration” when adjusting the process count of ProcessPoolExecutor.

  • bpo-42158: Add MIME types for N-quads, N-triples, Notation3 and TriG to mimetypes.

  • bpo-30533: Add inspect.getmembers_static() , it return all members without triggering dynamic lookup via the descriptor protocol. Patch by Weipeng Hong.

Documentação

  • bpo-42238: make -C Doc suspicious will be removed soon in favor of make -C Doc check, mark it as deprecated.

  • bpo-45840: Improve cross-references in the documentation for the data model.

  • bpo-45640: Properly marked-up grammar tokens in the documentation are now clickable and take you to the definition of a given piece of grammar. Patch by Arthur Milchior.

  • bpo-45788: Link doc for sys.prefix to sysconfig doc on installation paths.

  • bpo-45772: socket.socket documentation is corrected to a class from a function.

  • bpo-45392: Update the docstring of the type built-in to remove a redundant line and to mention keyword arguments for the constructor.

  • bpo-45250: Update the documentation to note that CPython does not consistently require iterators to define __iter__.

  • bpo-25381: In the extending chapter of the extending doc, update a paragraph about the global variables containing exception information.

  • bpo-43905: Expanded astuple() and asdict() docs, warning about deepcopy being applied and providing a workaround.

Testes

  • bpo-45695: Out-of-tree builds with a read-only source directory are now tested by CI.

  • bpo-19460: Add new Test for Lib/email/mime/nonmultipart.py::MIMENonMultipart.

  • bpo-45835: Fix race condition in test_queue tests with multiple “feeder” threads.

  • bpo-45783: The test for the freeze tool now handles file moves and deletions.

  • bpo-45745: Remove the --findleaks command line option of regrtest: use the --fail-env-changed option instead. Since Python 3.7, it was a deprecated alias to the --fail-env-changed option.

  • bpo-45701: Add tests with tuple type with functools.lru_cache() to test_functools.

Construção

  • bpo-44035: CI now verifies that autoconf files have been regenerated with a current and unpatched autoconf package.

  • bpo-45950: The build system now uses a _bootstrap_python interpreter for freezing and deepfreezing again. To speed up build process the build tools _bootstrap_python and _freeze_module are no longer build with LTO.

  • bpo-45881: The configure script now accepts --with-build-python and --with-freeze-module options to make cross compiling easier.

  • bpo-40280: Emscripten platform now uses .wasm suffix by default.

  • bpo-40280: Disable unusable core extension modules on WASM/Emscripten targets.

  • bpo-40280: configure now checks for socket shutdown function. The check makes it possible to disable SYS_shutdown with ac_cv_func_shutdown=no in CONFIG_SITE.

  • bpo-40280: configure now checks for functions fork1, getegid, geteuid, getgid, getppid, getuid, opendir, pipe, system, wait, ttyname.

  • bpo-33393: Update config.guess to 2021-06-03 and config.sub to 2021-08-14. Makefile now has an update-config target to make updating more convenient.

  • bpo-45866: make regen-all now produces the same output when run from a directory other than the source tree: when building Python out of the source tree. pegen now strips directory of the “generated by pygen from <FILENAME>” header Patch by Victor Stinner.

  • bpo-40280: configure now accepts machine wasm32 or wasm64 and OS wasi or emscripten for cross building, e.g. wasm32-unknown-emscripten, wasm32-wasi, or wasm32-unknown-wasi.

  • bpo-41498: Python now compiles on platforms without sigset_t. Several functions in signal are not available when sigset_t is missing.

    Based on patch by Roman Yurchak for pyodide.

  • bpo-45881: setup.py now uses CC from environment first to discover multiarch and cross compile paths.

  • bpo-45886: The _freeze_module program path can now be overridden on the command line, e.g. make FREEZE_MODULE=../x86_64/Program/_freeze_module.

  • bpo-45873: Get rid of the _bootstrap_python build step. The deepfreeze.py script is now run using $(PYTHON_FOR_REGEN) which can be Python 3.7 or newer (on Windows, 3.8 or newer).

  • bpo-45847: Port builtin hashlib extensions to PY_STDLIB_MOD macro and addext().

  • bpo-45723: Add autoconf helpers for saving and restoring environment variables:

    • SAVE_ENV: Save $CFLAGS, $LDFLAGS, $LIBS, and $CPPFLAGS.

    • RESTORE_ENV: Restore $CFLAGS, $LDFLAGS, $LIBS, and $CPPFLAGS.

    • WITH_SAVE_ENV([SCRIPT]): Run SCRIPT wrapped with SAVE_ENV and RESTORE_ENV.

    Patch por Erlend E. Aasland.

  • bpo-45573: Mandatory core modules, that are required to bootstrap Python, are now in Modules/Setup.bootstrap.

  • bpo-45573: configure now creates Modules/Setup.stdlib with conditionally enabled/disabled extension module lines. The file is not used, yet.

  • bpo-45573: configure now uses a unified format to set state, compiler flags, and linker flags in Makefile. The new macro PY_STDLIB_MOD sets three variables that are consumed by Modules/Setup and setup.py.

  • bpo-45816: Python now supports building with Visual Studio 2022 (MSVC v143, VS Version 17.0). Patch by Jeremiah Vivian.

  • bpo-45800: Settings for pyexpat C extension are now detected by configure. The bundled expat library is built in Makefile.

  • bpo-45798: Settings for decimal internal C extension are now detected by configure. The bundled libmpdec library is built in Makefile.

  • bpo-45723: configure has a new option --with-pkg-config to disable or require pkg-config.

  • bpo-45774: The build dependencies for sqlite3 are now detected by configure and pkg-config. Patch by Erlend E. Aasland.

  • bpo-45763: The build dependencies for zlib, bz2, and lzma are now detected by configure.

  • bpo-45747: gdbm and dbm build dependencies are now detected by configure.

  • bpo-45743: On macOS, the build system no longer passes search_paths_first to the linker. The flag has been the default since Xcode 4 / macOS 10.6.

  • bpo-45723: configure.ac is now compatible with autoconf 2.71. Deprecated checks STDC_HEADERS and AC_HEADER_TIME have been removed.

  • bpo-45723: configure now prints a warning when pkg-config is missing.

  • bpo-45731: configure --enable-loadable-sqlite-extensions is now handled by new PY_SQLITE_ENABLE_LOAD_EXTENSION macro instead of logic in setup.py.

  • bpo-45723: configure.ac now uses custom helper macros and AC_CACHE_CHECK to simplify and speed up configure runs.

  • bpo-45696: Skip the marshal step for frozen modules by generating C code that produces a set of ready-to-use code objects. This speeds up startup time by another 10% or more.

  • bpo-45561: Run smelly.py tool from $(srcdir).

Windows

  • bpo-46105: Fixed calculation of sys.path in a venv on Windows.

  • bpo-45901: When installed through the Microsoft Store and set as the default app for *.py files, command line arguments will now be passed to Python when invoking a script without explicitly launching Python (that is, script.py args rather than python script.py args).

  • bpo-45616: Fix Python Launcher’s ability to distinguish between versions 3.1 and 3.10 when either one is explicitly requested. Previously, 3.1 would be used if 3.10 was requested but not installed, and 3.10 would be used if 3.1 was requested but 3.10 was installed.

  • bpo-45850: Implement changes to build with deep-frozen modules on Windows. Note that we now require Python 3.10 as the “bootstrap” or “host” Python.

  • bpo-45732: Updates bundled Tcl/Tk to 8.6.12.

  • bpo-45720: Internal reference to shlwapi.dll was dropped to help improve startup time. This DLL will no longer be loaded at the start of every Python process.

macOS

  • bpo-45732: Update python.org macOS installer to use Tcl/Tk 8.6.12.

API C

  • bpo-39026: Fix Python.h to build C extensions with Xcode: remove a relative include from Include/cpython/pystate.h.

Python 3.11.0 alpha 2

Data de lançamento: 2021-11-05

Núcleo e embutidos

  • bpo-45716: Improve the SyntaxError message when using True, None or False as keywords in a function call. Patch by Pablo Galindo.

  • bpo-45688: sys.stdlib_module_names now contains the macOS-specific module _scproxy.

  • bpo-45379: Clarify ImportError message when we try to explicitly import a frozen module but frozen modules are disabled.

  • bpo-44525: Specialize simple calls to Python functions (no starargs, keyword dict, or closure)

  • bpo-45530: Cases of sorting using tuples as keys may now be significantly faster in some cases. Patch by Tim Peters.

    The order of the result may differ from earlier releases if the tuple elements don’t define a total ordering (see Comparações de valor for information on total ordering). It’s generally true that the result of sorting simply isn’t well-defined in the absence of a total ordering on list elements.

  • bpo-45526: In obmalloc, set ADDRESS_BITS to not ignore any bits (ignored 16 before). That is safer in the case that the kernel gives user-space virtual addresses that span a range greater than 48 bits.

  • bpo-30570: Fixed a crash in issubclass() from infinite recursion when searching pathological __bases__ tuples.

  • bpo-45521: Fix a bug in the obmalloc radix tree code. On 64-bit machines, the bug causes the tree to hold 46-bits of virtual addresses, rather than the intended 48-bits.

  • bpo-45494: Fix parser crash when reporting errors involving invalid continuation characters. Patch by Pablo Galindo.

  • bpo-45445: Python now fails to initialize if it finds an invalid -X option in the command line. Patch by Pablo Galindo.

  • bpo-45340: Object attributes are held in an array instead of a dictionary. An object’s dictionary are created lazily, only when needed. Reduces the memory consumption of a typical Python object by about 30%. Patch by Mark Shannon.

  • bpo-45408: Fix a crash in the parser when reporting tokenizer errors that occur at the same time unclosed parentheses are detected. Patch by Pablo Galindo.

  • bpo-29410: Add SipHash13 for string hash algorithm and use it by default.

  • bpo-45385: Fix reference leak from descr_check. Patch by Donghee Na.

  • bpo-45367: Specialized the BINARY_MULTIPLY opcode to BINARY_MULTIPLY_INT and BINARY_MULTIPLY_FLOAT using the PEP 659 machinery.

  • bpo-21736: Frozen stdlib modules now have __file__ to the .py file they would otherwise be loaded from, if possible. For packages, __path__ now has the correct entry instead of being an empty list, which allows unfrozen submodules to be imported. These are set only if the stdlib directory is known when the runtime is initialized. Note that the file at __file__ is not guaranteed to exist. None of this affects non-stdlib frozen modules nor, for now, frozen modules imported using PyImport_ImportFrozenModule(). Also, at the moment co_filename is not updated for the module.

  • bpo-45020: For frozen stdlib modules, record the original module name as module.__spec__.loader_state.origname. If the value is different than module.__spec__.name then the module was defined as an alias in Tools/scripts/freeze_modules.py. If it is None then the module comes from a source file outside the stdlib.

  • bpo-45324: In FrozenImporter.find_spec(), we now preserve the information needed in exec_module() to load the module. This change mostly impacts internal details, rather than changing the importer’s behavior.

  • bpo-45292: Implement PEP 654. Add ExceptionGroup and BaseExceptionGroup. Update traceback display code.

  • bpo-40116: Change to the implementation of split dictionaries. Classes where the instances differ either in the exact set of attributes, or in the order in which those attributes are set, can still share keys. This should have no observable effect on users of Python or the C-API. Patch by Mark Shannon.

  • bpo-44050: Extensions that indicate they use global state (by setting m_size to -1) can again be used in multiple interpreters. This reverts to behavior of Python 3.8.

  • bpo-44525: Setup initial specialization infrastructure for the CALL_FUNCTION opcode. Implemented initial specializations for C function calls:

    • CALL_FUNCTION_BUILTIN_O for METH_O flag.

    • CALL_FUNCTION_BUILTIN_FAST for METH_FASTCALL flag without keywords.

    • CALL_FUNCTION_LEN for len(o).

    • CALL_FUNCTION_ISINSTANCE for isinstance(o, t).

  • bpo-44511: Improve the generated bytecode for class and mapping patterns.

  • bpo-43706: Speed up calls to enumerate() by using the PEP 590 vectorcall calling convention. Patch by Donghee Na.

Biblioteca

  • bpo-45679: Fix caching of multi-value typing.Literal. Literal[True, 2] is no longer equal to Literal[1, 2].

  • bpo-42064: Convert sqlite3 to multi-phase initialisation (PEP 489). Patches by Erlend E. Aasland.

  • bpo-45438: Fix typing.Signature string representation for generic builtin types.

  • bpo-45613: sqlite3 now sets sqlite3.threadsafety based on the default threading mode the underlying SQLite library has been compiled with. Patch by Erlend E. Aasland.

  • bpo-45574: Fix warning about print_escape being unused.

  • bpo-45581: sqlite3.connect() now correctly raises MemoryError if the underlying SQLite API signals memory error. Patch by Erlend E. Aasland.

  • bpo-45557: pprint.pprint() now handles underscore_numbers correctly. Previously it was always setting it to False.

  • bpo-44019: Add operator.call() to operator.__all__. Patch by Kreusada.

  • bpo-42174: shutil.get_terminal_size() now falls back to sane values if the column or line count are 0.

  • bpo-35673: Improve the introspectability of the __loader__ attribute for namespace packages. importlib.machinery.NamespaceLoader is now public, and implements the importlib.abc.InspectLoader interface. _NamespaceLoader is kept for backward compatibility.

  • bpo-45515: Add references to zoneinfo in the datetime documentation, mostly replacing outdated references to dateutil.tz. Change by Paul Ganssle.

  • bpo-45475: Reverted optimization of iterating gzip.GzipFile, bz2.BZ2File, and lzma.LZMAFile (see bpo-43787) because it caused regression when user iterate them without having reference of them. Patch by Inada Naoki.

  • bpo-45489: Update ForwardRef to support | operator. Patch by Donghee Na.

  • bpo-42222: Removed deprecated support for float arguments in randrange().

  • bpo-45428: Fix a regression in py_compile when reading filenames from standard input.

  • bpo-45467: Fix incremental decoder and stream reader in the “raw-unicode-escape” codec. Previously they failed if the escape sequence was split.

  • bpo-45461: Fix incremental decoder and stream reader in the “unicode-escape” codec. Previously they failed if the escape sequence was split.

  • bpo-45239: Fixed email.utils.parsedate_tz() crashing with UnboundLocalError on certain invalid input instead of returning None. Patch by Ben Hoyt.

  • bpo-45417: Fix quadratic behaviour in the enum module: Creation of enum classes with a lot of entries was quadratic.

  • bpo-45249: Fix the behaviour of traceback.print_exc() when displaying the caret when the end_offset in the exception is set to 0. Patch by Pablo Galindo

  • bpo-45416: Fix use of asyncio.Condition with explicit asyncio.Lock objects, which was a regression due to removal of explicit loop arguments. Patch by Joongi Kim.

  • bpo-20028: Empty escapechar/quotechar is not allowed when initializing csv.Dialect. Patch by Vajrasky Kok and Donghee Na.

  • bpo-44904: Fix bug in the doctest module that caused it to fail if a docstring included an example with a classmethod property. Patch by Alex Waygood.

  • bpo-45406: Make inspect.getmodule() catch FileNotFoundError raised by inspect.getabsfile(), and return None to indicate that the module could not be determined.

  • bpo-45411: Add extensions for files containing subtitles - .srt & .vtt - to the mimetypes.py module.

  • bpo-10716: Migrated pydoc to HTML5 (without changing the look of it). Side effect is to update xmlrpc’s ServerHTMLDoc which now uses the CSS too. cgitb now relies less on pydoc (as it can’t use the CSS file).

  • bpo-27580: Add support of null characters in csv.

  • bpo-45262: Prevent use-after-free in asyncio. Make sure the cached running loop holder gets cleared on dealloc to prevent use-after-free in get_running_loop

  • bpo-45386: Make xmlrpc.client more robust to C runtimes where the underlying C strftime function results in a ValueError when testing for year formatting options.

  • bpo-20028: Improve error message of csv.Dialect when initializing. Patch by Vajrasky Kok and Donghee Na.

  • bpo-45343: Update bundled pip to 21.2.4 and setuptools to 58.1.0

  • bpo-45328: Fixed http.client.HTTPConnection to work properly in OSs that don’t support the TCP_NODELAY socket option.

  • bpo-45243: Add setlimit() and getlimit() to sqlite3.Connection for setting and getting SQLite limits by connection basis. Patch by Erlend E. Aasland.

  • bpo-45320: Removed from the inspect module:

    Patch por Hugo van Kemenade.

  • bpo-45192: Fix the tempfile._infer_return_type function so that the dir argument of the tempfile functions accepts an object implementing the os.PathLike protocol.

    Patch by Kyungmin Lee.

  • bpo-45160: When tracing a tkinter variable used by a ttk OptionMenu, callbacks are no longer made twice.

  • bpo-25625: Added non parallel-safe chdir() context manager to change the current working directory and then restore it on exit. Simple wrapper around chdir().

  • bpo-24139: Add support for SQLite extended result codes in sqlite3.Error. Patch by Erlend E. Aasland.

  • bpo-24444: Fixed an error raised in argparse help display when help for an option is set to 1+ blank spaces or when choices arg is an empty container.

  • bpo-44547: Implement Fraction.__int__, so that a fractions.Fraction instance f passes an isinstance(f, typing.SupportsInt) check.

  • bpo-40321: Adds support for HTTP 308 redirects to urllib. See RFC 7538 for details. Patch by Jochem Schulenklopper.

  • bpo-41374: Ensure that socket.TCP_* constants are exposed on Cygwin 3.1.6 and greater.

  • bpo-35970: Add help flag to the base64 module’s command line interface. Patch contributed by Robert Kuska.

Documentação

  • bpo-45726: Improve documentation for functools.singledispatch() and functools.singledispatchmethod.

  • bpo-45680: Amend the docs on GenericAlias objects to clarify that non-container classes can also implement __class_getitem__. Patch contributed by Alex Waygood.

  • bpo-45618: Update Sphinx version used to build the documentation to 4.2.0. Patch by Maciej Olko.

  • bpo-45655: Add a new “relevant PEPs” section to the top of the documentation for the typing module. Patch by Alex Waygood.

  • bpo-45604: Add level argument to multiprocessing.log_to_stderr function docs.

  • bpo-45516: Add protocol description to the importlib.abc.TraversableResources documentation.

  • bpo-45464: Mention in the documentation of Built-in Exceptions that inheriting from multiple exception types in a single subclass is not recommended due to possible memory layout incompatibility.

  • bpo-45449: Add note about PEP 585 in collections.abc.

  • bpo-45516: Add protocol description to the importlib.abc.Traversable documentation.

  • bpo-20692: Add Programming FAQ entry explaining that int literal attribute access requires either a space after or parentheses around the literal.

Testes

  • bpo-45678: Add tests for scenarios in which functools.singledispatchmethod is stacked on top of a method that has already been wrapped by two other decorators. Patch by Alex Waygood.

  • bpo-45578: Add tests for dis.distb()

  • bpo-45678: Add tests to ensure that functools.singledispatchmethod correctly wraps the attributes of the target function.

  • bpo-45668: PGO tests now pass when Python is built without test extension modules.

  • bpo-45577: Add subtests for all pickle protocols in test_zoneinfo.

  • bpo-45566: Fix test_frozen_pickle in test_dataclasses to check all pickle versions.

  • bpo-43592: test.libregrtest now raises the soft resource limit for the maximum number of file descriptors when the default is too low for our test suite as was often the case on macOS.

  • bpo-39679: Add more test cases for @functools.singledispatchmethod when combined with @classmethod or @staticmethod.

  • bpo-45410: When libregrtest spawns a worker process, stderr is now written into stdout to keep messages order. Use a single pipe for stdout and stderr, rather than two pipes. Previously, messages were out of order which made analysis of buildbot logs harder Patch by Victor Stinner.

  • bpo-45402: Fix test_tools.test_sundry() when Python is built out of tree: fix how the freeze_modules.py tool locates the _freeze_module program. Patch by Victor Stinner.

  • bpo-45403: Fix test_sys.test_stdlib_dir() when Python is built outside the source tree: compare normalized paths. Patch by Victor Stinner.

  • bpo-45400: Fix test_name_error_suggestions_do_not_trigger_for_too_many_locals() of test_exceptions if a directory name contains “a1” (like “Python-3.11.0a1”): use a stricter regular expression. Patch by Victor Stinner.

  • bpo-10572: Rename sqlite3 tests from test_sqlite to test_sqlite3, and relocate them to Lib/test/test_sqlite3. Patch by Erlend E. Aasland.

Construção

  • bpo-43158: setup.py now uses values from configure script to build the _uuid extension module. Configure now detects util-linux’s libuuid, too.

  • bpo-45666: Fix warning of swprintf and %s usage in _testembed.c

  • bpo-45548: Modules/Setup and Modules/makesetup have been improved. The Setup file now contains working rules for all extensions. Outdated comments have been removed. Rules defined by makesetup track dependencies correctly.

  • bpo-45548: The math and cmath implementation now require a C99 compatible libm and no longer ship with workarounds for missing acosh, asinh, atanh, expm1, and log1p functions.

  • bpo-45595: setup.py and makesetup now track build dependencies on all Python header files and module specific header files.

  • bpo-45571: Modules/Setup now use PY_CFLAGS_NODIST instead of PY_CFLAGS to compile shared modules.

  • bpo-45570: pyexpat and _elementtree no longer define obsolete macros HAVE_EXPAT_CONFIG_H and USE_PYEXPAT_CAPI. XML_POOR_ENTROPY is now defined in expat_config.h.

  • bpo-43974: setup.py no longer defines Py_BUILD_CORE_MODULE. Instead every module, that uses the internal API, defines the macro.

  • bpo-45548: Fill in missing entries in Modules/Setup.

  • bpo-45532: Update sys.version to use main as fallback information. Patch by Jeong YunWon.

  • bpo-45536: The configure script now checks whether OpenSSL headers and libraries provide required APIs. Most common APIs are verified. The check detects outdated or missing OpenSSL. Failures do not stop configure.

  • bpo-45221: Fixed regression in handling of LDFLAGS and CPPFLAGS options where argparse.parse_known_args() could interpret an option as one of the built-in command line argument, for example -h for help.

  • bpo-45440: Building Python now requires a C99 <math.h> header file providing the following functions: copysign(), hypot(), isfinite(), isinf(), isnan(), round(). Patch by Victor Stinner.

  • bpo-45405: Prevent internal configure error when running configure with recent versions of non-Apple clang. Patch by David Bohman.

  • bpo-45433: Avoid linking libpython with libcrypt.

Windows

  • bpo-43652: Update Tcl/Tk to 8.6.11, actually this time. The previous update incorrectly included 8.6.10.

  • bpo-45337: venv now warns when the created environment may need to be accessed at a different path, due to redirections, links or junctions. It also now correctly installs or upgrades components when the alternate path is required.

  • bpo-43851: Build SQLite SQLITE_OMIT_AUTOINIT on Windows. Patch by Erlend E. Aasland.

macOS

  • bpo-44828: Avoid tkinter file dialog failure on macOS 12 Monterey when using the Tk 8.6.11 provided by python.org macOS installers. Patch by Marc Culler of the Tk project.

IDLE

  • bpo-45495: Add context keywords ‘case’ and ‘match’ to completions list.

API C

  • bpo-29103: PyType_FromSpec* now copies the class name from the spec to a buffer owned by the class, so the original can be safely deallocated. Patch by Petr Viktorin.

  • bpo-45522: The internal freelists for frame, float, list, dict, async generators, and context objects can now be disabled.

  • bpo-35134: Exclude PyWeakref_GET_OBJECT() from the limited C API. It never worked since the PyWeakReference structure is opaque in the limited C API.

  • bpo-35081: Move the interpreteridobject.h header file from Include/ to Include/internal/. It only provides private functions. Patch by Victor Stinner.

  • bpo-35134: The non-limited API files cellobject.h, classobject.h, context.h, funcobject.h, genobject.h and longintrepr.h have been moved to the Include/cpython directory. Moreover, the eval.h header file was removed. These files must not be included directly, as they are already included in Python.h: Include Files. If they have been included directly, consider including Python.h instead. Patch by Victor Stinner.

  • bpo-45474: The following items are no longer available when Py_LIMITED_API is defined:

    Eles não fazem parte da API limitada.

    Patch por Victor Stinner.

  • bpo-45434: Remove the pystrhex.h header file. It only contains private functions. C extensions should only include the main <Python.h> header file. Patch by Victor Stinner.

  • bpo-45440: Remove the Py_FORCE_DOUBLE() macro. It was used by the Py_IS_INFINITY() macro. Patch by Victor Stinner.

  • bpo-45434: <Python.h> no longer includes the header files <stdlib.h>, <stdio.h>, <errno.h> and <string.h> when the Py_LIMITED_API macro is set to 0x030b0000 (Python 3.11) or higher. C extensions should explicitly include the header files after #include <Python.h>. Patch by Victor Stinner.

  • bpo-41123: Remove Py_UNICODE_COPY() and Py_UNICODE_FILL() macros, deprecated since Python 3.3. Use PyUnicode_CopyCharacters() or memcpy() (wchar_t* string), and PyUnicode_Fill() functions instead. Patch by Victor Stinner.

  • bpo-45412: Remove the following math macros using the errno variable:

    • Py_ADJUST_ERANGE1()

    • Py_ADJUST_ERANGE2()

    • Py_OVERFLOWED()

    • Py_SET_ERANGE_IF_OVERFLOW()

    • Py_SET_ERRNO_ON_MATH_ERROR()

    Patch por Victor Stinner.

  • bpo-45395: Custom frozen modules (the array set to PyImport_FrozenModules) are now treated as additions, rather than replacing all the default frozen modules. Frozen stdlib modules can still be disabled by setting the “code” field of the custom array entry to NULL.

  • bpo-43760: Add new PyThreadState_EnterTracing(), and PyThreadState_LeaveTracing() functions to the limited C API to suspend and resume tracing and profiling. Patch by Victor Stinner.

  • bpo-44220: PyStructSequence_UnnamedField is added to the Stable ABI.

Python 3.11.0 alpha 1

Data de lançamento: 2021-10-05

Segurança

  • bpo-42278: Replaced usage of tempfile.mktemp() with TemporaryDirectory to avoid a potential race condition.

  • bpo-44600: Fix incorrect line numbers while tracing some failed patterns in match statements. Patch by Charles Burkland.

  • bpo-41180: Add auditing events to the marshal module, and stop raising code.__init__ events for every unmarshalled code object. Directly instantiated code objects will continue to raise an event, and audit event handlers should inspect or collect the raw marshal data. This reduces a significant performance overhead when loading from .pyc files.

  • bpo-44394: Update the vendored copy of libexpat to 2.4.1 (from 2.2.8) to get the fix for the CVE 2013-0340 “Billion Laughs” vulnerability. This copy is most used on Windows and macOS.

  • bpo-43124: Made the internal putcmd function in smtplib sanitize input for presence of \r and \n characters to avoid (unlikely) command injection.

  • bpo-44022: http.client now avoids infinitely reading potential HTTP headers after a 100 Continue status response from the server.

Núcleo e embutidos

  • bpo-43760: The number of hardware branches per instruction dispatch is reduced from two to one by adding a special instruction for tracing. Patch by Mark Shannon.

  • bpo-45061: Add a deallocator to the bool type to detect refcount bugs in C extensions which call Py_DECREF(Py_True) or Py_DECREF(Py_False) by mistake. Detect also refcount bugs when the empty tuple singleton or the Unicode empty string singleton is destroyed by mistake. Patch by Victor Stinner.

  • bpo-24076: sum() was further optimised for summing up single digit integers.

  • bpo-45190: Update Unicode databases to Unicode 14.0.0.

  • bpo-45167: Fix deepcopying of types.GenericAlias objects.

  • bpo-45155: int.to_bytes() and int.from_bytes() now take a default value of "big" for the byteorder argument. int.to_bytes() also takes a default value of 1 for the length argument.

Biblioteca

Núcleo e embutidos

  • bpo-44959: Added fallback to extension modules with ‘.sl’ suffix on HP-UX

Biblioteca

  • bpo-45121: Fix issue where Protocol.__init__ raises RecursionError when it’s called directly or via super(). Patch provided by Yurii Karabas.

Núcleo e embutidos

  • bpo-44348: The deallocator function of the BaseException type now uses the trashcan mechanism to prevent stack overflow. For example, when a RecursionError instance is raised, it can be linked to another RecursionError through the __context__ attribute or the __traceback__ attribute, and then a chain of exceptions is created. When the chain is destroyed, nested deallocator function calls can crash with a stack overflow if the chain is too long compared to the available stack memory. Patch by Victor Stinner.

  • bpo-45123: Fix PyAiter_Check to only check for the __anext__ presence (not for __aiter__). Rename PyAiter_Check to PyAIter_Check, PyObject_GetAiter -> PyObject_GetAIter.

  • bpo-1514420: Interpreter no longer attempts to open files with names in angle brackets (like “<string>” or “<stdin>”) when formatting an exception.

  • bpo-41031: Match C and Python code formatting of unprintable exceptions and exceptions in the __main__ module.

  • bpo-37330: open(), io.open(), codecs.open() and fileinput.FileInput no longer accept 'U' (“universal newline”) in the file mode. This flag was deprecated since Python 3.3. Patch by Victor Stinner.

  • bpo-45083: When the interpreter renders an exception, its name now has a complete qualname. Previously only the class name was concatenated to the module name, which sometimes resulted in an incorrect full name being displayed.

    (This issue impacted only the C code exception rendering, the traceback module was using qualname already).

  • bpo-34561: List sorting now uses the merge-ordering strategy from Munro and Wild’s powersort(). Unlike the former strategy, this is provably near-optimal in the entropy of the distribution of run lengths. Most uses of list.sort() probably won’t see a significant time difference, but may see significant improvements in cases where the former strategy was exceptionally poor. However, as these are all fast linear-time approximations to a problem that’s inherently at best quadratic-time to solve truly optimally, it’s also possible to contrive cases where the former strategy did better.

  • bpo-45056: Compiler now removes trailing unused constants from co_consts.

  • bpo-45020: Add a new command line option, “-X frozen_modules=[on|off]” to opt out of (or into) using optional frozen modules. This defaults to “on” (or “off” if it’s running out of the source tree).

Biblioteca

Núcleo e embutidos

  • bpo-45018: Fixed pickling of range iterators that iterated for over 2**32 times.

  • bpo-45000: A SyntaxError is now raised when trying to delete __debug__. Patch by Donghee Na.

  • bpo-44963: Implement send() and throw() methods for anext_awaitable objects. Patch by Pablo Galindo.

Biblioteca

  • bpo-44962: Fix a race in WeakKeyDictionary, WeakValueDictionary and WeakSet when two threads attempt to commit the last pending removal. This fixes asyncio.create_task and fixes a data loss in asyncio.run where shutdown_asyncgens is not run

Núcleo e embutidos

  • bpo-24234: Implement the __bytes__() special method on the bytes type, so a bytes object b passes an isinstance(b, typing.SupportsBytes) check.

  • bpo-24234: Implement the __complex__() special method on the complex type, so a complex number z passes an isinstance(z, typing.SupportsComplex) check.

  • bpo-44954: Fixed a corner case bug where the result of float.fromhex('0x.8p-1074') was rounded the wrong way.

  • bpo-44947: Refine the syntax error for trailing commas in import statements. Patch by Pablo Galindo.

  • bpo-44945: Specialize the BINARY_ADD instruction using the PEP 659 machinery. Adds five new instructions:

    • BINARY_ADD_ADAPTIVE

    • BINARY_ADD_FLOAT

    • BINARY_ADD_INT

    • BINARY_ADD_UNICODE

    • BINARY_ADD_UNICODE_INPLACE_FAST

Biblioteca

  • bpo-44929: Fix some edge cases of enum.Flag string representation in the REPL. Patch by Pablo Galindo.

Núcleo e embutidos

  • bpo-44914: Class version tags are no longer recycled.

    This means that a version tag serves as a unique identifier for the state of a class. We rely on this for effective specialization of the LOAD_ATTR and other instructions.

  • bpo-44698: Restore behaviour of complex exponentiation with integer-valued exponent of type float or complex.

  • bpo-44895: A debug variable PYTHONDUMPREFSFILE is added for creating a dump file which is generated by --with-trace-refs. Patch by Donghee Na.

  • bpo-44900: Add five superinstructions for PEP 659 quickening:

    • LOAD_FAST LOAD_FAST

    • STORE_FAST LOAD_FAST

    • LOAD_FAST LOAD_CONST

    • LOAD_CONST LOAD_FAST

    • STORE_FAST STORE_FAST

  • bpo-44889: Initial implementation of adaptive specialization of LOAD_METHOD. The following specialized forms were added:

    • LOAD_METHOD_CACHED

    • LOAD_METHOD_MODULE

    • LOAD_METHOD_CLASS

  • bpo-44890: Specialization stats are always collected in debug builds.

  • bpo-44885: Correct the ast locations of f-strings with format specs and repeated expressions. Patch by Pablo Galindo

  • bpo-44878: Remove the loop from the bytecode interpreter. All instructions end with a DISPATCH macro, so the loop is now redundant.

  • bpo-44878: Remove switch statement for interpreter loop when using computed gotos. This makes sure that we only have one dispatch table in the interpreter.

  • bpo-44874: Deprecate the old trashcan macros (Py_TRASHCAN_SAFE_BEGIN/Py_TRASHCAN_SAFE_END). They should be replaced by the new macros Py_TRASHCAN_BEGIN and Py_TRASHCAN_END.

  • bpo-44872: Use new trashcan macros (Py_TRASHCAN_BEGIN/END) in frameobject.c instead of the old ones (Py_TRASHCAN_SAFE_BEGIN/END).

  • bpo-33930: Fix segmentation fault with deep recursion when cleaning method objects. Patch by Augusto Goulart and Pablo Galindo.

  • bpo-25782: Fix bug where PyErr_SetObject hangs when the current exception has a cycle in its context chain.

  • bpo-44856: Fix reference leaks in the error paths of update_bases() and __build_class__. Patch by Pablo Galindo.

  • bpo-44826: Initial implementation of adaptive specialization of STORE_ATTR

    Three specialized forms of STORE_ATTR are added:

    • STORE_ATTR_SLOT

    • STORE_ATTR_SPLIT_KEYS

    • STORE_ATTR_WITH_HINT

  • bpo-44838: Fixed a bug that was causing the parser to raise an incorrect custom SyntaxError for invalid ‘if’ expressions. Patch by Pablo Galindo.

  • bpo-44821: Create instance dictionaries (__dict__) eagerly, to improve regularity of object layout and assist specialization.

  • bpo-44792: Improve syntax errors for if expressions. Patch by Miguel Brito

  • bpo-34013: Generalize the invalid legacy statement custom error message (like the one generated when “print” is called without parentheses) to include more generic expressions. Patch by Pablo Galindo

  • bpo-44732: Rename types.Union to types.UnionType.

  • bpo-44725: Expose specialization stats in python via _opcode.get_specialization_stats().

  • bpo-44717: Improve AttributeError on circular imports of submodules.

  • bpo-44698: Fix undefined behaviour in complex object exponentiation.

  • bpo-44653: Support typing types in parameter substitution in the union type.

  • bpo-44676: Add ability to serialise types.Union objects. Patch provided by Yurii Karabas.

  • bpo-44633: Parameter substitution of the union type with wrong types now raises TypeError instead of returning NotImplemented.

  • bpo-44661: Update property_descr_set to use vectorcall if possible. Patch by Donghee Na.

  • bpo-44662: Add __module__ to types.Union. This also fixes types.Union issues with typing.Annotated. Patch provided by Yurii Karabas.

  • bpo-44655: Include the name of the type in unset __slots__ attribute errors. Patch by Pablo Galindo

  • bpo-44655: Don’t include a missing attribute with the same name as the failing one when offering suggestions for missing attributes. Patch by Pablo Galindo

  • bpo-44646: Fix the hash of the union type: it no longer depends on the order of arguments.

  • bpo-44636: Collapse union of equal types. E.g. the result of int | int is now int. Fix comparison of the union type with non-hashable objects. E.g. int | str == {} no longer raises a TypeError.

Biblioteca

  • bpo-44611: On Windows, os.urandom(): uses BCryptGenRandom API instead of CryptGenRandom API which is deprecated from Microsoft Windows API. Patch by Donghee Na.

Núcleo e embutidos

  • bpo-44635: Convert None to type(None) in the union type constructor.

  • bpo-26280: Implement adaptive specialization for BINARY_SUBSCR

    Three specialized forms of BINARY_SUBSCR are added:

    • BINARY_SUBSCR_LIST_INT

    • BINARY_SUBSCR_TUPLE_INT

    • BINARY_SUBSCR_DICT

  • bpo-44589: Mapping patterns in match statements with two or more equal literal keys will now raise a SyntaxError at compile-time.

  • bpo-44606: Fix __instancecheck__ and __subclasscheck__ for the union type.

  • bpo-42073: The @classmethod decorator can now wrap other classmethod-like descriptors.

  • bpo-41972: Tuned the string-searching algorithm of fastsearch.h to have a shorter inner loop for most cases.

  • bpo-44590: All necessary data for executing a Python function (local variables, stack, etc) is now kept in a per-thread stack. Frame objects are lazily allocated on demand. This increases performance by about 7% on the standard benchmark suite. Introspection and debugging are unaffected as frame objects are always available when needed. Patch by Mark Shannon.

  • bpo-44584: The threading debug (PYTHONTHREADDEBUG environment variable) is deprecated in Python 3.10 and will be removed in Python 3.12. This feature requires a debug build of Python. Patch by Victor Stinner.

  • bpo-43895: An obsolete internal cache of shared object file handles added in 1995 that attempted, but did not guarantee, that a .so would not be dlopen’ed twice to work around flaws in mid-1990s posix-ish operating systems has been removed from dynload_shlib.c.

Biblioteca

  • bpo-44490: typing now searches for type parameters in types.Union objects. get_type_hints will also properly resolve annotations with nested types.Union objects. Patch provided by Yurii Karabas.

Núcleo e embutidos

  • bpo-43950: Code objects can now provide the column information for instructions when available. This is levaraged during traceback printing to show the expressions responsible for errors.

    Contributed by Pablo Galindo, Batuhan Taskaya and Ammar Askar as part of PEP 657.

  • bpo-44562: Remove uses of PyObject_GC_Del() in error path when initializing types.GenericAlias.

Biblioteca

  • bpo-41486: Fix a memory consumption and copying performance regression in earlier 3.10 beta releases if someone used an output buffer larger than 4GiB with zlib.decompress on input data that expands that large.

Núcleo e embutidos

  • bpo-43908: Heap types with the Py_TPFLAGS_IMMUTABLETYPE flag can now inherit the PEP 590 vectorcall protocol. Previously, this was only possible for static types. Patch by Erlend E. Aasland.

  • bpo-44553: Implement GC methods for types.Union to break reference cycles and prevent memory leaks.

  • bpo-44490: Add __parameters__ attribute and __getitem__ operator to types.Union. Patch provided by Yurii Karabas.

  • bpo-44523: Remove the pass-through for hash() of weakref.proxy objects to prevent unintended consequences when the original referred object dies while the proxy is part of a hashable object. Patch by Pablo Galindo.

  • bpo-44483: Fix a crash in types.Union objects when creating a union of an object with bad __module__ field.

  • bpo-44486: Modules will always have a dictionary, even when created by types.ModuleType.__new__()

  • bpo-44472: Fix ltrace functionality when exceptions are raised. Patch by Pablo Galindo

  • bpo-12022: A TypeError is now raised instead of an AttributeError in with and async with statements for objects which do not support the context manager or asynchronous context manager protocols correspondingly.

  • bpo-44297: Make sure that the line number is set when entering a comprehension scope. This ensures that backtraces including generator expressions show the correct line number.

  • bpo-44456: Improve the syntax error when mixing positional and keyword patterns. Patch by Pablo Galindo.

  • bpo-44409: Fix error location information for tokenizer errors raised on initialization of the tokenizer. Patch by Pablo Galindo.

  • bpo-44396: Fix a possible crash in the tokenizer when raising syntax errors for unclosed strings. Patch by Pablo Galindo.

  • bpo-44376: Exact integer exponentiation (like i**2 or pow(i, 2)) with a small exponent is much faster, due to reducing overhead in such cases.

  • bpo-44313: Directly imported objects and modules (through import and from import statements) don’t generate LOAD_METHOD/CALL_METHOD for directly accessed objects on their namespace. They now use the regular LOAD_ATTR/CALL_FUNCTION.

  • bpo-44338: Implement adaptive specialization for LOAD_GLOBAL

    Two specialized forms of LOAD_GLOBAL are added:

    • LOAD_GLOBAL_MODULE

    • LOAD_GLOBAL_BUILTIN

  • bpo-44368: Improve syntax errors for invalid “as” targets. Patch by Pablo Galindo

  • bpo-44349: Fix an edge case when displaying text from files with encoding in syntax errors. Patch by Pablo Galindo.

  • bpo-44337: Initial implementation of adaptive specialization of LOAD_ATTR

    Four specialized forms of LOAD_ATTR are added:

    • LOAD_ATTR_SLOT

    • LOAD_ATTR_SPLIT_KEYS

    • LOAD_ATTR_WITH_HINT

    • LOAD_ATTR_MODULE

  • bpo-44335: Fix a regression when identifying incorrect characters in syntax errors. Patch by Pablo Galindo

  • bpo-43693: Computation of the offsets of cell variables is done in the compiler instead of at runtime. This reduces the overhead of handling cell and free variables, especially in the case where a variable is both an argument and cell variable.

  • bpo-44317: Improve tokenizer error with improved locations. Patch by Pablo Galindo.

Biblioteca

  • bpo-44304: Fix a crash in the sqlite3 module that happened when the garbage collector clears sqlite.Statement objects. Patch by Pablo Galindo

Núcleo e embutidos

  • bpo-44305: Improve error message for try blocks without except or finally blocks. Patch by Pablo Galindo.

  • bpo-43413: Constructors of subclasses of some builtin classes (e.g. tuple, list, frozenset) no longer accept arbitrary keyword arguments. [reverted in 3.11a4] Subclass of set can now define a __new__() method with additional keyword parameters without overriding also __init__().

  • bpo-43667: Improve Unicode support in non-UTF locales on Oracle Solaris. This issue does not affect other Solaris systems.

  • bpo-43693: A new opcode MAKE_CELL has been added that effectively moves some of the work done on function entry into the compiler and into the eval loop. In addition to creating the required cell objects, the new opcode converts relevant arguments (and other locals) to cell variables on function entry.

  • bpo-44232: Fix a regression in type() when a metaclass raises an exception. The C function type_new() must properly report the exception when a metaclass constructor raises an exception and the winner class is not the metaclass. Patch by Victor Stinner.

  • bpo-44201: Avoid side effects of checking for specialized syntax errors in the REPL that was causing it to ask for extra tokens after a syntax error had been detected. Patch by Pablo Galindo

  • bpo-43693: PyCodeObject gained co_fastlocalnames and co_fastlocalkinds as the authoritative source of fast locals info. Marshaled code objects have changed accordingly.

  • bpo-44184: Fix a crash at Python exit when a deallocator function removes the last strong reference to a heap type. Patch by Victor Stinner.

  • bpo-44187: Implement quickening in the interpreter. This offers no advantages as yet, but is an enabler of future optimizations. See PEP 659 for full explanation.

  • bpo-44180: The parser doesn’t report generic syntax errors that happen in a position further away that the one it reached in the first pass. Patch by Pablo Galindo

  • bpo-44168: Fix error message in the parser involving keyword arguments with invalid expressions. Patch by Pablo Galindo

  • bpo-44156: String caches in compile.c are now subinterpreter compatible.

  • bpo-44143: Fixed a crash in the parser that manifest when raising tokenizer errors when an existing exception was present. Patch by Pablo Galindo.

  • bpo-44032: Move ‘fast’ locals and other variables from the frame object to a per-thread datastack.

  • bpo-44114: Correção de assinaturas incorretas das funções dictkeys_reversed e dictitems_reversed no código C, que quebrou a construção do WebAssembly.

  • bpo-44110: Improve str.__getitem__() error message

  • bpo-26110: Add CALL_METHOD_KW opcode to speed up method calls with keyword arguments. Idea originated from PyPy. A side effect is executing CALL_METHOD is now branchless in the evaluation loop.

  • bpo-28307: Compiler now optimizes simple C-style formatting with literal format containing only format codes %s, %r and %a by converting them to f-string expressions.

  • bpo-43149: Correct the syntax error message regarding multiple exception types to not refer to “exception groups”. Patch by Pablo Galindo

  • bpo-43822: The parser will prioritize tokenizer errors over custom syntax errors when raising exceptions. Patch by Pablo Galindo.

  • bpo-40222: “Zero cost” exception handling.

    • Uses a lookup table to determine how to handle exceptions.

    • Removes SETUP_FINALLY and POP_TOP block instructions, eliminating the runtime overhead of try statements.

    • Reduces the size of the frame object by about 60%.

    Patch by Mark Shannon

  • bpo-43918: Document the signature and default argument in the docstring of the new anext builtin.

  • bpo-43833: Emit a deprecation warning if the numeric literal is immediately followed by one of keywords: and, else, for, if, in, is, or. Raise a syntax error with more informative message if it is immediately followed by other keyword or identifier.

  • bpo-43879: Add native_thread_id to PyThreadState. Patch by Gabriele N. Tornetta.

  • bpo-43693: Compute cell offsets relative to locals in compiler. Allows the interpreter to treats locals and cells a single array, which is slightly more efficient. Also make the LOAD_CLOSURE opcode an alias for LOAD_FAST. Preserving LOAD_CLOSURE helps keep bytecode a bit more readable.

  • bpo-17792: More accurate error messages for access of unbound locals or free vars.

  • bpo-28146: Fix a confusing error message in str.format().

  • bpo-11105: When compiling ast.AST objects with recursive references through compile(), the interpreter doesn’t crash anymore instead it raises a RecursionError.

  • bpo-39091: Fix crash when using passing a non-exception to a generator’s throw() method. Patch by Noah Oxer

  • bpo-33346: Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.

Biblioteca

  • bpo-45371: Fix clang rpath issue in distutils. The UnixCCompiler now uses correct clang option to add a runtime library directory (rpath) to a shared library.

  • bpo-45329: Fix freed memory access in pyexpat.xmlparser when building it with an installed expat library <= 2.2.0.

  • bpo-41710: On Unix, if the sem_clockwait() function is available in the C library (glibc 2.30 and newer), the threading.Lock.acquire() method now uses the monotonic clock (time.CLOCK_MONOTONIC) for the timeout, rather than using the system clock (time.CLOCK_REALTIME), to not be affected by system clock changes. Patch by Victor Stinner.

  • bpo-1596321: Fix the threading._shutdown() function when the threading module was imported first from a thread different than the main thread: no longer log an error at Python exit.

  • bpo-45274: Fix a race condition in the Thread.join() method of the threading module. If the function is interrupted by a signal and the signal handler raises an exception, make sure that the thread remains in a consistent state to prevent a deadlock. Patch by Victor Stinner.

  • bpo-21302: In Unix operating systems, time.sleep() now uses the nanosleep() function, if clock_nanosleep() is not available but nanosleep() is available. nanosleep() allows to sleep with nanosecond precision.

  • bpo-21302: On Windows, time.sleep() now uses a waitable timer which has a resolution of 100 nanoseconds (10-7 seconds). Previously, it had a resolution of 1 millisecond (10-3 seconds). Patch by Benjamin Szőke and Victor Stinner.

  • bpo-45238: Fix unittest.IsolatedAsyncioTestCase.debug(): it runs now asynchronous methods and callbacks.

  • bpo-36674: unittest.TestCase.debug() raises now a unittest.SkipTest if the class or the test method are decorated with the skipping decorator.

  • bpo-45235: Fix an issue where argparse would not preserve values in a provided namespace when using a subparser with defaults.

  • bpo-45183: Have zipimport.zipimporter.find_spec() not raise an exception when the underlying zip file has been deleted and the internal cache has been reset via invalidate_cache().

  • bpo-45234: Fixed a regression in copyfile(), copy(), copy2() raising FileNotFoundError when source is a directory, which should raise IsADirectoryError

  • bpo-45228: Fix stack buffer overflow in parsing J1939 network address.

  • bpo-45225: use map function instead of genexpr in capwords.

  • bpo-42135: Fix typo: importlib.find_loader is really slated for removal in Python 3.12 not 3.10, like the others in PR 25169.

    Patch por Hugo van Kemenade.

  • bpo-20524: Improves error messages on .format() operation for str, float, int, and complex. New format now shows the problematic pattern and the object type.

  • bpo-45168: Change dis.dis() output to omit op arg values that cannot be resolved due to co_consts, co_names etc not being provided. Previously the oparg itself was repeated in the value field, which is not useful and can be confusing.

  • bpo-21302: In Unix operating systems, time.sleep() now uses the clock_nanosleep() function, if available, which allows to sleep for an interval specified with nanosecond precision.

  • bpo-45173: Remove from the configparser module: the SafeConfigParser class, the filename property of the ParsingError class, the readfp() method of the ConfigParser class, deprecated since Python 3.2.

    Patch por Hugo van Kemenade.

  • bpo-44987: Pure ASCII strings are now normalized in constant time by unicodedata.normalize(). Patch by Donghee Na.

  • bpo-35474: Calling mimetypes.guess_all_extensions() with strict=False no longer affects the result of the following call with strict=True. Also, mutating the returned list no longer affects the global state.

  • bpo-45166: typing.get_type_hints() now works with Final wrapped in ForwardRef.

  • bpo-45162: Remove many old deprecated unittest features:

    • “fail*” and “assert*” aliases of TestCase methods.

    • Broken from start TestCase method assertDictContainsSubset().

    • Ignored <unittest.TestLoader.loadTestsFromModule> TestLoader.loadTestsFromModule() parameter use_load_tests.

    • Old alias _TextTestResult of TextTestResult.

  • bpo-38371: Remove the deprecated split() method of _tkinter.TkappType. Patch by Erlend E. Aasland.

  • bpo-20499: Improve the speed and accuracy of statistics.pvariance().

  • bpo-45132: Remove __getitem__() methods of xml.dom.pulldom.DOMEventStream, wsgiref.util.FileWrapper and fileinput.FileInput, deprecated since Python 3.9.

    Patch por Hugo van Kemenade.

  • bpo-45129: Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint(), disabled in Python 3.9, is now entirely removed. This is because of the behavior of the socket option SO_REUSEADDR in UDP.

    Patch por Hugo van Kemenade.

  • bpo-45124: The bdist_msi command, deprecated in Python 3.9, is now removed.

    Use bdist_wheel (wheel packages) instead.

    Patch por Hugo van Kemenade.

  • bpo-30856: unittest.TestResult methods addFailure(), addError(), addSkip() and addSubTest() are now called immediately after raising an exception in test or finishing a subtest. Previously they were called only after finishing the test clean up.

  • bpo-45034: Changes how error is formatted for struct.pack with 'H' and 'h' modes and too large / small numbers. Now it shows the actual numeric limits, while previously it was showing arithmetic expressions.

  • bpo-25894: unittest now always reports skipped and failed subtests separately: separate characters in default mode and separate lines in verbose mode. Also the test description is now output for errors in test method, class and module cleanups.

  • bpo-45081: Fix issue when dataclasses that inherit from typing.Protocol subclasses have wrong __init__. Patch provided by Yurii Karabas.

  • bpo-45085: The binhex module, deprecated in Python 3.9, is now removed. The following binascii functions, deprecated in Python 3.9, are now also removed:

    • a2b_hqx(), b2a_hqx();

    • rlecode_hqx(), rledecode_hqx().

    A função binascii.crc_hqx() continua disponível.

    Patch por Victor Stinner.

  • bpo-40360: The lib2to3 package is now deprecated and may not be able to parse Python 3.10 or newer. See the PEP 617 (New PEG parser for CPython). Patch by Victor Stinner.

  • bpo-45075: Rename traceback.StackSummary.format_frame() to traceback.StackSummary.format_frame_summary(). This method was added for 3.11 so it was not released yet.

    Updated code and docs to better distinguish frame and FrameSummary.

  • bpo-31299: Add option to completely drop frames from a traceback by returning None from a format_frame() override.

  • bpo-41620: run() now always return a TestResult instance. Previously it returned None if the test class or method was decorated with a skipping decorator.

  • bpo-45021: Fix a potential deadlock at shutdown of forked children when using concurrent.futures module

  • bpo-43913: Fix bugs in cleaning up classes and modules in unittest:

    • Functions registered with addModuleCleanup() were not called unless the user defines tearDownModule() in their test module.

    • Functions registered with addClassCleanup() were not called if tearDownClass is set to None.

    • Buffering in TestResult did not work with functions registered with addClassCleanup() and addModuleCleanup().

    • Errors in functions registered with addClassCleanup() and addModuleCleanup() were not handled correctly in buffered and debug modes.

    • Errors in setUpModule() and functions registered with addModuleCleanup() were reported in wrong order.

    • And several lesser bugs.

  • bpo-45030: Fix integer overflow in pickling and copying the range iterator.

  • bpo-45001: Made email date parsing more robust against malformed input, namely a whitespace-only Date: header. Patch by Wouter Bolsterlee.

  • bpo-45010: Remove support of special method __div__ in unittest.mock. It is not used in Python 3.

  • bpo-39218: Improve accuracy of variance calculations by using x*x instead of x**2.

  • bpo-43613: Improve the speed of gzip.compress() and gzip.decompress() by compressing and decompressing at once in memory instead of in a streamed fashion.

  • bpo-37596: Ensure that set and frozenset objects are always marshalled reproducibly.

  • bpo-44019: A new function operator.call has been added, such that operator.call(obj, *args, **kwargs) == obj(*args, **kwargs).

  • bpo-42255: webbrowser.MacOSX is deprecated and will be removed in Python 3.13. It is untested and undocumented and also not used by webbrowser itself. Patch by Donghee Na.

  • bpo-44955: Method stopTestRun() is now always called in pair with method startTestRun() for TestResult objects implicitly created in run(). Previously it was not called for test methods and classes decorated with a skipping decorator.

  • bpo-39039: tarfile.open raises ReadError when a zlib error occurs during file extraction.

  • bpo-44935: subprocess on Solaris now also uses os.posix_spawn() for better performance.

  • bpo-44911: IsolatedAsyncioTestCase will no longer throw an exception while cancelling leaked tasks. Patch by Bar Harel.

  • bpo-41322: Added DeprecationWarning for tests and async tests that return a value!=None (as this may indicate an improperly written test, for example a test written as a generator function).

  • bpo-44524: Make exception message more useful when subclass from typing special form alias. Patch provided by Yurii Karabas.

  • bpo-38956: argparse.BooleanOptionalAction’s default value is no longer printed twice when used with argparse.ArgumentDefaultsHelpFormatter.

  • bpo-44860: Fix the posix_user scheme in sysconfig to not depend on sys.platlibdir.

  • bpo-44859: Improve error handling in sqlite3 and raise more accurate exceptions.

    • MemoryError is now raised instead of sqlite3.Warning when memory is not enough for encoding a statement to UTF-8 in Connection.__call__() and Cursor.execute().

    • UnicodEncodeError is now raised instead of sqlite3.Warning when the statement contains surrogate characters in Connection.__call__() and Cursor.execute().

    • TypeError is now raised instead of ValueError for non-string script argument in Cursor.executescript().

    • ValueError is now raised for script containing the null character instead of truncating it in Cursor.executescript().

    • Correctly handle exceptions raised when getting boolean value of the result of the progress handler.

    • Add many tests covering different corner cases.

  • bpo-44581: Upgrade bundled pip to 21.2.3 and setuptools to 57.4.0

  • bpo-44849: Fix the os.set_inheritable() function on FreeBSD 14 for file descriptor opened with the O_PATH flag: ignore the EBADF error on ioctl(), fallback on the fcntl() implementation. Patch by Victor Stinner.

  • bpo-44605: The @functools.total_ordering() decorator now works with metaclasses.

  • bpo-44524: Fixed an issue wherein the __name__ and __qualname__ attributes of subscribed specialforms could be None.

  • bpo-44839: MemoryError raised in user-defined functions will now produce a MemoryError in sqlite3. OverflowError will now be converted to DataError. Previously OperationalError was produced in these cases.

  • bpo-44822: sqlite3 user-defined functions and aggregators returning strings with embedded NUL characters are no longer truncated. Patch by Erlend E. Aasland.

  • bpo-44801: Ensure that the ParamSpec variable in Callable can only be substituted with a parameters expression (a list of types, an ellipsis, ParamSpec or Concatenate).

  • bpo-44806: Non-protocol subclasses of typing.Protocol ignore now the __init__ method inherited from protocol base classes.

  • bpo-27275: collections.OrderedDict.popitem() and collections.OrderedDict.pop() no longer call __getitem__ and __delitem__ methods of the OrderedDict subclasses.

  • bpo-44793: Fix checking the number of arguments when subscribe a generic type with ParamSpec parameter.

  • bpo-44784: In importlib.metadata tests, override warnings behavior under expected DeprecationWarnings (importlib_metadata 4.6.3).

  • bpo-44667: The tokenize.tokenize() doesn’t incorrectly generate a NEWLINE token if the source doesn’t end with a new line character but the last line is a comment, as the function is already generating a NL token. Patch by Pablo Galindo

  • bpo-44771: Added importlib.simple module implementing adapters from a low-level resources reader interface to a TraversableResources interface. Legacy API (path, contents, …) is now supported entirely by the .files() API with a compatibility shim supplied for resource loaders without that functionality. Feature parity with importlib_resources 5.2.

  • bpo-44752: rcompleter does not call getattr() on property objects to avoid the side-effect of evaluating the corresponding method.

  • bpo-44747: Refactor usage of sys._getframe in typing module. Patch provided by Yurii Karabas.

  • bpo-42378: Fixes the issue with log file being overwritten when logging.FileHandler is used in atexit with filemode set to 'w'. Note this will cause the message in atexit not being logged if the log stream is already closed due to shutdown of logging.

  • bpo-44720: weakref.proxy objects referencing non-iterators now raise TypeError rather than dereferencing the null tp_iternext slot and crashing.

  • bpo-44704: The implementation of collections.abc.Set._hash() now matches that of frozenset.__hash__().

  • bpo-44666: Fixed issue in compileall.compile_file() when sys.stdout is redirected. Patch by Stefan Hölzl.

  • bpo-44688: sqlite3.Connection.create_collation() now accepts non-ASCII collation names. Patch by Erlend E. Aasland.

  • bpo-44690: Adopt binacii.a2b_base64’s strict mode in base64.b64decode.

  • bpo-42854: Fixed a bug in the _ssl module that was throwing OverflowError when using _ssl._SSLSocket.write() and _ssl._SSLSocket.read() for a big value of the len parameter. Patch by Pablo Galindo.

  • bpo-44686: Replace unittest.mock._importer with pkgutil.resolve_name.

  • bpo-44353: Make NewType.__call__ faster by implementing it in C. Patch provided by Yurii Karabas.

  • bpo-44682: Change the pdb commands directive to disallow setting commands for an invalid breakpoint and to display an appropriate error.

  • bpo-44353: Refactor typing.NewType from function into callable class. Patch provided by Yurii Karabas.

  • bpo-44678: Added a separate error message for discontinuous padding in binascii.a2b_base64 strict mode.

  • bpo-44524: Add missing __name__ and __qualname__ attributes to typing module classes. Patch provided by Yurii Karabas.

  • bpo-40897: Give priority to using the current class constructor in inspect.signature(). Patch by Weipeng Hong.

  • bpo-44638: Add a reference to the zipp project and hint as to how to use it.

  • bpo-44648: Fixed wrong error being thrown by inspect.getsource() when examining a class in the interactive session. Instead of TypeError, it should be OSError with appropriate error message.

  • bpo-44608: Fix memory leak in _tkinter._flatten() if it is called with a sequence or set, but not list or tuple.

  • bpo-44594: Fix an edge case of ExitStack and AsyncExitStack exception chaining. They will now match with block behavior when __context__ is explicitly set to None when the exception is in flight.

  • bpo-42799: In fnmatch, the cache size for compiled regex patterns (functools.lru_cache()) was bumped up from 256 to 32768, affecting functions: fnmatch.fnmatch(), fnmatch.fnmatchcase(), fnmatch.filter().

  • bpo-41928: Update shutil.copyfile() to raise FileNotFoundError instead of confusing IsADirectoryError when a path ending with a os.path.sep does not exist; shutil.copy() and shutil.copy2() are also affected.

  • bpo-44569: Added the StackSummary.format_frame() function in traceback. This allows users to customize the way individual lines are formatted in tracebacks without re-implementing logic to handle recursive tracebacks.

  • bpo-44566: handle StopIteration subclass raised from @contextlib.contextmanager generator

  • bpo-44558: Make the implementation consistency of indexOf() between C and Python versions. Patch by Donghee Na.

  • bpo-41249: Fixes TypedDict to work with typing.get_type_hints() and postponed evaluation of annotations across modules.

  • bpo-44554: Refactor argument processing in pdb.main() to simplify detection of errors in input loading and clarify behavior around module or script invocation.

  • bpo-34798: Break up paragraph about pprint.PrettyPrinter construction parameters to make it easier to read.

  • bpo-44539: Added support for recognizing JPEG files without JFIF or Exif markers.

  • bpo-44461: Fix bug with pdb’s handling of import error due to a package which does not have a __main__ module

  • bpo-43625: Fix a bug in the detection of CSV file headers by csv.Sniffer.has_header() and improve documentation of same.

  • bpo-44516: Update vendored pip to 21.1.3

  • bpo-42892: Fixed an exception thrown while parsing a malformed multipart email by email.message.EmailMessage.

  • bpo-44468: typing.get_type_hints() now finds annotations in classes and base classes with unexpected __module__. Previously, it skipped those MRO elements.

  • bpo-44491: Allow clearing the sqlite3 authorizer callback by passing None to set_authorizer(). Patch by Erlend E. Aasland.

  • bpo-43977: Set the proper Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE flags for subclasses created before a parent has been registered as a collections.abc.Mapping or collections.abc.Sequence.

  • bpo-44482: Fix very unlikely resource leak in glob in alternate Python implementations.

  • bpo-44466: The faulthandler module now detects if a fatal error occurs during a garbage collector collection. Patch by Victor Stinner.

  • bpo-44471: A TypeError is now raised instead of an AttributeError in contextlib.ExitStack.enter_context() and contextlib.AsyncExitStack.enter_async_context() for objects which do not support the context manager or asynchronous context manager protocols correspondingly.

  • bpo-44404: tkinter’s after() method now supports callables without the __name__ attribute.

  • bpo-41546: Make pprint (like the builtin print) not attempt to write to stdout when it is None.

  • bpo-44458: BUFFER_BLOCK_SIZE is now declared static, to avoid linking collisions when bz2, lmza or zlib are statically linked.

  • bpo-44464: Remove exception for flake8 in deprecated importlib.metadata interfaces. Sync with importlib_metadata 4.6.

  • bpo-44446: Take into account that lineno might be None in traceback.FrameSummary.

  • bpo-44439: Fix in bz2.BZ2File.write() / lzma.LZMAFile.write() methods, when the input data is an object that supports the buffer protocol, the file length may be wrong.

  • bpo-44434: _thread.start_new_thread() no longer calls PyThread_exit_thread() explicitly at the thread exit, the call was redundant. On Linux with the glibc, pthread_exit() aborts the whole process if dlopen() fails to open libgcc_s.so file (ex: EMFILE error). Patch by Victor Stinner.

  • bpo-42972: The _thread.RLock type now fully implement the GC protocol: add a traverse function and the Py_TPFLAGS_HAVE_GC flag. Patch by Victor Stinner.

  • bpo-44422: The threading.enumerate() function now uses a reentrant lock to prevent a hang on reentrant call. Patch by Victor Stinner.

  • bpo-38291: Importing typing.io or typing.re now prints a DeprecationWarning.

  • bpo-37880: argparse actions store_const and append_const each receive a default value of None when the const kwarg is not provided. Previously, this raised a TypeError.

  • bpo-44389: Fix deprecation of ssl.OP_NO_TLSv1_3

  • bpo-27827: pathlib.PureWindowsPath.is_reserved() now identifies a greater range of reserved filenames, including those with trailing spaces or colons.

  • bpo-44395: Fix as_string() to pass unixfrom properly. Patch by Donghee Na.

  • bpo-34266: Handle exceptions from parsing the arg of pdb’s run/restart command.

  • bpo-44362: Improve ssl module’s deprecation messages, error reporting, and documentation for deprecations.

  • bpo-44342: [Enum] Change pickling from by-value to by-name.

  • bpo-44356: [Enum] Allow multiple data-type mixins if they are all the same.

  • bpo-44351: Restore back parse_makefile() in distutils.sysconfig because it behaves differently than the similar implementation in sysconfig.

  • bpo-35800: smtpd.MailmanProxy is now removed as it is unusable without an external module, mailman. Patch by Donghee Na.

  • bpo-44357: Added a function that returns cube root of the given number math.cbrt()

  • bpo-44339: Change math.pow(±0.0, -math.inf) to return inf instead of raising ValueError. This brings the special-case handling of math.pow into compliance with the IEEE 754 standard.

  • bpo-44242: Remove missing flag check from Enum creation and move into a verify decorator.

  • bpo-44246: In importlib.metadata, restore compatibility in the result from Distribution.entry_points (EntryPoints) to honor expectations in older implementations and issuing deprecation warnings for these cases: A. EntryPoints objects are once again mutable, allowing for sort() and other list-based mutation operations. Avoid deprecation warnings by casting to a mutable sequence (e.g. list(dist.entry_points).sort()). B. EntryPoints results once again allow for access by index. To avoid deprecation warnings, cast the result to a Sequence first (e.g. tuple(dist.entry_points)[0]).

  • bpo-44246: In importlib.metadata.entry_points, de-duplication of distributions no longer requires loading the full metadata for PathDistribution objects, improving entry point loading performance by ~10x.

  • bpo-43858: Added a function that returns a copy of a dict of logging levels: logging.getLevelNamesMapping()

  • bpo-44260: The random.Random constructor no longer reads system entropy without need.

  • bpo-44254: On Mac, give turtledemo button text a color that works on both light or dark background. Programmers cannot control the latter.

  • bpo-44258: Support PEP 515 for Fraction’s initialization from string.

  • bpo-44235: Remove deprecated functions in the gettext. Patch by Donghee Na.

  • bpo-38693: Prefer f-strings to .format in importlib.resources.

  • bpo-33693: Importlib.metadata now prefers f-strings to .format.

  • bpo-44241: Incorporate minor tweaks from importlib_metadata 4.1: SimplePath protocol, support for Metadata 2.2.

  • bpo-43216: Remove the @asyncio.coroutine decorator enabling legacy generator-based coroutines to be compatible with async/await code; remove asyncio.coroutines.CoroWrapper used for wrapping legacy coroutine objects in the debug mode. The decorator has been deprecated since Python 3.8 and the removal was initially scheduled for Python 3.10. Patch by Illia Volochii.

  • bpo-44210: Make importlib.metadata._meta.PackageMetadata public.

  • bpo-43643: Declare readers.MultiplexedPath.name as a property per the spec.

  • bpo-27334: The sqlite3 context manager now performs a rollback (thus releasing the database lock) if commit failed. Patch by Luca Citi and Erlend E. Aasland.

  • bpo-4928: Documented existing behavior on POSIX: NamedTemporaryFiles are not deleted when creating process is killed with SIGKILL

  • bpo-44154: Optimize fractions.Fraction pickling for large components.

  • bpo-33433: For IPv4 mapped IPv6 addresses (RFC 4291 Section 2.5.5.2), the ipaddress.IPv6Address.is_private check is deferred to the mapped IPv4 address. This solves a bug where public mapped IPv4 addresses were considered private by the IPv6 check.

  • bpo-44150: Add optional weights argument to statistics.fmean().

  • bpo-44142: ast.unparse() will now drop the redundant parentheses when tuples used as assignment targets (e.g in for loops).

  • bpo-44145: hmac computations were not releasing the GIL while calling the OpenSSL HMAC_Update C API (a new feature in 3.9). This unintentionally prevented parallel computation as other hashlib algorithms support.

  • bpo-44095: zipfile.Path now supports zipfile.Path.stem, zipfile.Path.suffixes, and zipfile.Path.suffix attributes.

  • bpo-44077: It’s now possible to receive the type of service (ToS), a.k.a. differentiated services (DS), a.k.a. differentiated services code point (DSCP) and explicit congestion notification (ECN) IP header fields with socket.IP_RECVTOS.

  • bpo-37788: Fix a reference leak when a Thread object is never joined.

  • bpo-38908: Subclasses of typing.Protocol which only have data variables declared will now raise a TypeError when checked with isinstance unless they are decorated with runtime_checkable(). Previously, these checks passed silently. Patch provided by Yurii Karabas.

  • bpo-44098: typing.ParamSpec will no longer be found in the __parameters__ of most typing generics except in valid use locations specified by PEP 612. This prevents incorrect usage like typing.List[P][int]. This change means incorrect usage which may have passed silently in 3.10 beta 1 and earlier will now error.

  • bpo-44089: Allow subclassing csv.Error in 3.10 (it was allowed in 3.9 and earlier but was disallowed in early versions of 3.10).

  • bpo-44081: ast.unparse() now doesn’t use redundant spaces to separate lambda and the : if there are no parameters.

  • bpo-44061: Fix regression in previous release when calling pkgutil.iter_modules() with a list of pathlib.Path objects

  • bpo-44059: Register the SerenityOS Browser in the webbrowser module.

  • bpo-36515: The hashlib module no longer does unaligned memory accesses when compiled for ARM platforms.

  • bpo-40465: Remove random module features deprecated in Python 3.9.

  • bpo-44018: random.seed() no longer mutates bytearray inputs.

  • bpo-38352: Add IO, BinaryIO, TextIO, Match, and Pattern to typing.__all__. Patch by Jelle Zijlstra.

  • bpo-44002: urllib.parse now uses functool.lru_cache() for its internal URL splitting and quoting caches instead of rolling its own like its the ‘90s.

    The undocumented internal urllib.parse Quoted class API is now deprecated, for removal in 3.14.

  • bpo-43972: When http.server.SimpleHTTPRequestHandler sends a 301 (Moved Permanently) for a directory path not ending with /, add a Content-Length: 0 header. This improves the behavior for certain clients.

  • bpo-28528: Fix a bug in pdb where checkline() raises AttributeError if it is called after reset().

  • bpo-43853: Improved string handling for sqlite3 user-defined functions and aggregates:

    • It is now possible to pass strings with embedded null characters to UDFs

    • Conversion failures now correctly raise MemoryError

    Patch por Erlend E. Aasland.

  • bpo-43666: AIX: Lib/_aix_support.get_platform() may fail in an AIX WPAR. The fileset bos.rte appears to have a builddate in both LPAR and WPAR so this fileset is queried rather than bos.mp64. To prevent a similar situation (no builddate in ODM) a value (9988) sufficient for completing a build is provided. Patch by M Felt.

  • bpo-43650: Fix MemoryError in shutil.unpack_archive() which fails inside shutil._unpack_zipfile() on large files. Patch by Igor Bolshakov.

  • bpo-43612: zlib.compress() now accepts a wbits parameter which allows users to compress data as a raw deflate block without zlib headers and trailers in one go. Previously this required instantiating a zlib.compressobj. It also provides a faster alternative to gzip.compress when wbits=31 is used.

  • bpo-43392: importlib._bootstrap._find_and_load() now implements a two-step check to avoid locking when modules have been already imported and are ready. This improves performance of repeated calls to importlib.import_module() and importlib.__import__().

  • bpo-43318: Fix a bug where pdb does not always echo cleared breakpoints.

  • bpo-43234: Prohibit passing non-concurrent.futures.ThreadPoolExecutor executors to loop.set_default_executor() following a deprecation in Python 3.8. Patch by Illia Volochii.

  • bpo-43232: Prohibit previously deprecated potentially disruptive operations on asyncio.trsock.TransportSocket. Patch by Illia Volochii.

  • bpo-30077: Added support for Apple’s aifc/sowt pseudo-compression

  • bpo-42971: Add definition of errno.EQFULL for platforms that define this constant (such as macOS).

  • bpo-43086: Added a new optional strict_mode parameter to binascii.a2b_base64. When scrict_mode is set to True, the a2b_base64 function will accept only valid base64 content. More details about what “valid base64 content” is, can be found in the function’s documentation.

  • bpo-43024: Improve the help signature of traceback.print_exception(), traceback.format_exception() and traceback.format_exception_only().

  • bpo-33809: Add the traceback.TracebackException.print() method which prints the formatted exception information.

  • bpo-42862: sqlite3 now utilizes functools.lru_cache() to implement the connection statement cache. As a small optimisation, the default statement cache size has been increased from 100 to 128. Patch by Erlend E. Aasland.

  • bpo-41818: Soumendra Ganguly: add termios.tcgetwinsize(), termios.tcsetwinsize().

  • bpo-40497: subprocess.check_output() now raises ValueError when the invalid keyword argument check is passed by user code. Previously such use would fail later with a TypeError. Patch by Rémi Lapeyre.

  • bpo-37449: ensurepip now uses importlib.resources.files() traversable APIs

  • bpo-40956: Use Argument Clinic in sqlite3. Patches by Erlend E. Aasland.

  • bpo-41730: DeprecationWarning is now raised when importing tkinter.tix, which has been deprecated in documentation since Python 3.6.

  • bpo-20684: Remove unused _signature_get_bound_param function from inspect - by Anthony Sottile.

  • bpo-41402: Fix email.message.EmailMessage.set_content() when called with binary data and 7bit content transfer encoding.

  • bpo-32695: The compresslevel and preset keyword arguments of tarfile.open() are now both documented and tested.

  • bpo-41137: Use utf-8 encoding while reading .pdbrc files. Patch by Srinivas Reddy Thatiparthy

  • bpo-24391: Improved reprs of threading synchronization objects: Semaphore, BoundedSemaphore, Event and Barrier.

  • bpo-5846: Deprecated the following unittest functions, scheduled for removal in Python 3.13:

    • findTestCases()

    • makeSuite()

    • getTestCaseNames()

    Em vez delas, use os métodos de TestLoader:

    Patch por Erlend E. Aasland.

  • bpo-40563: Support pathlike objects on dbm/shelve. Patch by Hakan Çelik and Henry-Joseph Audéoud.

  • bpo-34990: Fixed a Y2k38 bug in the compileall module where it would fail to compile files with a modification time after the year 2038.

  • bpo-39549: Whereas the code for reprlib.Repr had previously used a hardcoded string value of ‘…’, this PR updates it to use of a “fillvalue” attribute, whose value defaults to ‘…’ and can be reset in either individual reprlib.Repr instances or in subclasses thereof.

  • bpo-37022: pdb now displays exceptions from repr() with its p and pp commands.

  • bpo-38840: Fix test___all__ on platforms lacking a shared memory implementation.

  • bpo-39359: Add one missing check that the password is a bytes object for an encrypted zipfile.

  • bpo-38741: configparser: using ‘]’ inside a section header will no longer cut the section name short at the ‘]’

  • bpo-38415: Added missing behavior to contextlib.asynccontextmanager() to match contextlib.contextmanager() so decorated functions can themselves be decorators.

  • bpo-30256: Pass multiprocessing BaseProxy argument manager_owned through AutoProxy.

  • bpo-27513: email.utils.getaddresses() now accepts email.header.Header objects along with string values. Patch by Zackery Spytz.

  • bpo-16379: Add SQLite error code and name to sqlite3 exceptions. Patch by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland.

  • bpo-26228: pty.spawn no longer hangs on FreeBSD, macOS, and Solaris.

  • bpo-33349: lib2to3 now recognizes async generators everywhere.

  • bpo-29298: Fix TypeError when required subparsers without dest do not receive arguments. Patch by Anthony Sottile.

Documentação

  • bpo-45216: Remove extra documentation listing methods in difflib. It was rendering twice in pydoc and was outdated in some places.

  • bpo-45024: collections.abc documentation has been expanded to explicitly cover how instance and subclass checks work, with additional doctest examples and an exhaustive list of ABCs which test membership purely by presence of the right special methods. Patch by Raymond Hettinger.

  • bpo-44957: Promote PEP 604 union syntax by using it where possible. Also, mention X | Y more prominently in section about Union and mention X | None at all in section about Optional.

  • bpo-16580: Added code equivalents for the int.to_bytes() and int.from_bytes() methods, as well as tests ensuring that these code equivalents are valid.

  • bpo-44903: Removed the othergui.rst file, any references to it, and the list of GUI frameworks in the FAQ. In their place I’ve added links to the Python Wiki page on GUI frameworks.

  • bpo-33479: Tkinter documentation has been greatly expanded with new “Architecture” and “Threading model” sections.

  • bpo-36700: base64 RFC references were updated to point to RFC 4648; a section was added to point users to the new “security considerations” section of the RFC.

  • bpo-44740: Replaced occurrences of uppercase “Web” and “Internet” with lowercase versions per the 2016 revised Associated Press Style Book.

  • bpo-44693: Update the definition of __future__ in the glossary by replacing the confusing word “pseudo-module” with a more accurate description.

  • bpo-35183: Add typical examples to os.path.splitext docs

  • bpo-30511: Clarify that shutil.make_archive() is not thread-safe due to reliance on changing the current working directory.

  • bpo-44561: Update of three expired hyperlinks in Doc/distributing/index.rst: “Project structure”, “Building and packaging the project”, and “Uploading the project to the Python Packaging Index”.

  • bpo-44651: Delete entry “coercion” in Doc/glossary.rst for its outdated definition.

  • bpo-42958: Updated the docstring and docs of filecmp.cmp() to be more accurate and less confusing especially in respect to shallow arg.

  • bpo-44631: Refactored the repr() code of the _Environ (os module).

  • bpo-44613: importlib.metadata is no longer provisional.

  • bpo-44558: Match the docstring and python implementation of countOf() to the behavior of its c implementation.

  • bpo-44544: List all kwargs for textwrap.wrap(), textwrap.fill(), and textwrap.shorten(). Now, there are nav links to attributes of TextWrap, which makes navigation much easier while minimizing duplication in the documentation.

  • bpo-38062: Clarify that atexit uses equality comparisons internally.

  • bpo-40620: Convert examples in tutorial controlflow.rst section 4.3 to be interpreter-demo style.

  • bpo-43066: Added a warning to zipfile docs: filename arg with a leading slash may cause archive to be un-openable on Windows systems.

  • bpo-39452: Rewrote Doc/library/__main__.rst. Broadened scope of the document to explicitly discuss and differentiate between __main__.py in packages versus the __name__ == '__main__' expression (and the idioms that surround it).

  • bpo-13814: In the Design FAQ, answer “Why don’t generators support the with statement?”

  • bpo-27752: Documentation of csv.Dialect is more descriptive.

  • bpo-44453: Fix documentation for the return type of sysconfig.get_path().

  • bpo-44392: Added a new section in the C API documentation for types used in type hinting. Documented Py_GenericAlias and Py_GenericAliasType.

  • bpo-38291: Mark typing.io and typing.re as deprecated since Python 3.8 in the documentation. They were never properly supported by type checkers.

  • bpo-44322: Document that SyntaxError args have a details tuple and that details are adjusted for errors in f-string field replacement expressions.

  • bpo-42392: Document the deprecation and removal of the loop parameter for many functions and classes in asyncio.

  • bpo-44195: Corrected references to TraversableResources in docs. There is no TraversableReader.

  • bpo-41963: Document that ConfigParser strips off comments when reading configuration files.

  • bpo-44072: Correct where in the numeric ABC hierarchy ** support is added, i.e., in numbers.Complex, not numbers.Integral.

  • bpo-43558: Add the remark to dataclasses documentation that the __init__() of any base class has to be called in __post_init__(), along with a code example.

  • bpo-44025: Clarify when ‘_’ in match statements is a keyword, and when not.

  • bpo-41706: Fix docs about how methods like __add__ are invoked when evaluating operator expressions.

  • bpo-41621: Document that collections.defaultdict parameter default_factory defaults to None and is positional-only.

  • bpo-41576: document BaseException in favor of bare except

  • bpo-21760: The description for __file__ fixed. Patch by Furkan Onder

  • bpo-39498: Add a “Security Considerations” index which links to standard library modules that have explicitly documented security considerations.

  • bpo-33479: Remove the unqualified claim that tkinter is threadsafe. It has not been true for several years and likely never was. An explanation of what is true may be added later, after more discussion, and possibly after patching _tkinter.c,

Testes

  • bpo-40173: Fix test.support.import_helper.import_fresh_module().

  • bpo-45280: Add a test case for empty typing.NamedTuple.

  • bpo-45269: Cover case when invalid markers type is supplied to c_make_encoder.

  • bpo-45128: Fix test_multiprocessing_fork failure due to test_logging and sys.modules manipulation.

  • bpo-45209: Fix UserWarning: resource_tracker warning in _test_multiprocessing._TestSharedMemory.test_shared_memory_cleaned_after_process_termination

  • bpo-45185: Enables TestEnumerations test cases in test_ssl suite.

  • bpo-45195: Fix test_readline.test_nonascii(): sometimes, the newline character is not written at the end, so don’t expect it in the output. Patch by Victor Stinner.

  • bpo-45156: Fixes infinite loop on unittest.mock.seal() of mocks created by create_autospec().

  • bpo-45125: Improves pickling tests and docs of SharedMemory and SharableList objects.

  • bpo-44860: Update test_sysconfig.test_user_similar() for the posix_user scheme: platlib doesn’t use sys.platlibdir. Patch by Victor Stinner.

  • bpo-45052: WithProcessesTestSharedMemory.test_shared_memory_basics test was ignored, because self.assertEqual(sms.size, sms2.size) line was failing. It is now removed and test is unskipped.

    The main motivation for this line to be removed from the test is that the size of SharedMemory is not ever guaranteed to be the same. It is decided by the platform.

  • bpo-44895: libregrtest now clears the type cache later to reduce the risk of false alarm when checking for reference leaks. Previously, the type cache was cleared too early and libregrtest raised a false alarm about reference leaks under very specific conditions. Patch by Irit Katriel and Victor Stinner.

  • bpo-45042: Fixes that test classes decorated with @hashlib_helper.requires_hashdigest were skipped all the time.

  • bpo-25130: Add calls of gc.collect() in tests to support PyPy.

  • bpo-45011: Made tests relying on the _asyncio C extension module optional to allow running on alternative Python implementations. Patch by Serhiy Storchaka.

  • bpo-44949: Fix auto history tests of test_readline: sometimes, the newline character is not written at the end, so don’t expect it in the output.

  • bpo-44891: Tests were added to clarify id() is preserved when obj * 1 is used on str and bytes objects. Patch by Nikita Sobolev.

  • bpo-44852: Add ability to wholesale silence DeprecationWarnings while running the regression test suite.

  • bpo-40928: Notify users running test_decimal regression tests on macOS of potential harmless “malloc can’t allocate region” messages spewed by test_decimal.

  • bpo-44734: Fixed floating-point precision issue in turtle tests.

  • bpo-44708: Regression tests, when run with -w, are now re-running only the affected test methods instead of re-running the entire test file.

  • bpo-42095: Added interop tests for Apple plists: generate plist files with Python plistlib and parse with Apple plutil; and the other way round.

  • bpo-44647: Added a permanent Unicode-valued environment variable to regression tests to ensure they handle this use case in the future. If your test environment breaks because of that, report a bug to us, and temporarily set PYTHONREGRTEST_UNICODE_GUARD=0 in your test environment.

  • bpo-44515: Adjust recently added contextlib tests to avoid assuming the use of a refcounted GC

  • bpo-44287: Fix asyncio test_popen() of test_windows_utils by using a longer timeout. Use military grade battle-tested test.support.SHORT_TIMEOUT timeout rather than a hardcoded timeout of 10 seconds: it’s 30 seconds by default, but it is made longer on slow buildbots. Patch by Victor Stinner.

  • bpo-44451: Reset DeprecationWarning filters in test.test_importlib.test_metadata_api.APITests.test_entry_points_by_index to avoid StopIteration error if DeprecationWarnings are ignored.

  • bpo-44363: Account for address sanitizer in test_capi. test_capi now passes when run GCC address sanitizer.

  • bpo-44364: Add non integral tests for math.sqrt() function.

  • bpo-43921: Fix test_ssl.test_wrong_cert_tls13(): use suppress_ragged_eofs=False, since read() can raise ssl.SSLEOFError on Windows. Patch by Victor Stinner.

  • bpo-43921: Fix test_pha_required_nocert() of test_ssl: catch two more EOF cases (when the recv() method returns an empty string). Patch by Victor Stinner.

  • bpo-44131: Add test_frozenmain to test_embed to test the Py_FrozenMain() C function. Patch by Victor Stinner.

  • bpo-31904: Ignore error string case in test_file_not_exists().

  • bpo-42083: Add test to check that PyStructSequence_NewType accepts a PyStructSequence_Desc with doc field set to NULL.

  • bpo-35753: Fix crash in doctest when doctest parses modules that include unwrappable functions by skipping those functions.

  • bpo-30256: Add test for nested queues when using multiprocessing shared objects AutoProxy[Queue] inside ListProxy and DictProxy

Construção

  • bpo-45220: Avoid building with the Windows 11 SDK previews automatically. This may be overridden by setting the DefaultWindowsSDKVersion environment variable before building.

  • bpo-45020: Freeze stdlib modules that are imported during startup. This provides significant performance improvements to startup. If necessary, use the previously added “-X frozen_modules=off” commandline option to force importing the source modules.

  • bpo-45188: Windows builds now regenerate frozen modules as the first part of the build. Previously the regeneration was later in the build, which would require it to be restarted if any modules had changed.

  • bpo-45163: Fixes Haiku platform build.

  • bpo-45067: The ncurses function extended_color_content was introduced in 2017

    (https://invisible-island.net/ncurses/NEWS.html#index-t20170401). The

    ncurses-devel package in CentOS 7 had a older version ncurses resulted in compilation error. For compiling ncurses with extended color support, we verify the version of the ncurses library >= 20170401.

  • bpo-45019: Generate lines in relevant files for frozen modules. Up until now each of the files had to be edited manually. This change makes it easier to add to and modify the frozen modules.

  • bpo-44340: Add support for building with clang thin lto via –with-lto=thin/full. Patch by Donghee Na and Brett Holman.

  • bpo-44535: Enable building using a Visual Studio 2022 install on Windows.

  • bpo-43298: Improved error message when building without a Windows SDK installed.

  • bpo-44381: The Windows build now accepts EnableControlFlowGuard set to guard to enable CFG.

  • bpo-41282: Fix broken make install that caused standard library extension modules to be unnecessarily and incorrectly rebuilt during the install phase of cpython.

Windows

macOS

  • bpo-45007: Atualizadas as construções do instalador do macOS para utilizar OpenSSL 1.1.1l.

  • bpo-34602: When building CPython on macOS with ./configure --with-undefined-behavior-sanitizer --with-pydebug, the stack size is now quadrupled to allow for the entire test suite to pass.

  • bpo-44848: Update macOS installer to use SQLite 3.36.0.

  • bpo-44689: ctypes.util.find_library() now works correctly on macOS 11 Big Sur even if Python is built on an older version of macOS. Previously, when built on older macOS systems, find_library was not able to find macOS system libraries when running on Big Sur due to changes in how system libraries are stored.

  • bpo-41972: The framework build’s user header path in sysconfig is changed to add a ‘pythonX.Y’ component to match distutils’s behavior.

  • bpo-43109: Allow –with-lto configure option to work with Apple-supplied Xcode or Command Line Tools.

  • bpo-34932: Add socket.TCP_KEEPALIVE support for macOS. Patch by Shane Harvey.

IDLE

  • bpo-45296: On Windows, change exit/quit message to suggest Ctrl-D, which works, instead of <Ctrl-Z Return>, which does not work in IDLE.

  • bpo-45193: Make completion boxes appear on Ubuntu again.

  • bpo-40128: Mostly fix completions on macOS when not using tcl/tk 8.6.11 (as with 3.9). The added update_idletask call should be harmless and possibly helpful otherwise.

  • bpo-33962: Move the indent space setting from the Font tab to the new Windows tab. Patch by Mark Roseman and Terry Jan Reedy.

  • bpo-40468: Split the settings dialog General tab into Windows and Shell/ED tabs. Move help sources, which extend the Help menu, to the Extensions tab. Make space for new options and shorten the dialog. The latter makes the dialog better fit small screens.

  • bpo-41611: Avoid uncaught exceptions in AutoCompleteWindow.winconfig_event().

  • bpo-41611: Fix IDLE sometimes freezing upon tab-completion on macOS.

  • bpo-44010: Highlight the new match statement’s soft keywords: match, case, and _. However, this highlighting is not perfect and will be incorrect in some rare cases, including some _-s in case patterns.

  • bpo-44026: Include interpreter’s typo fix suggestions in message line for NameErrors and AttributeErrors. Patch by E. Paine.

Ferramentas/Demos

  • bpo-44786: Fix a warning in regular expression in the c-analyzer script.

  • bpo-44967: pydoc now returns a non-zero status code when a module cannot be found.

  • bpo-44978: Allow the Argument Clinic tool to handle __complex__ special methods.

  • bpo-43425: Removed the ‘test2to3’ demo project that demonstrated using lib2to3 to support Python 2.x and Python 3.x from a single source in a distutils package. Patch by Donghee Na

  • bpo-44074: Make patchcheck automatically detect the correct base branch name (previously it was hardcoded to ‘master’)

  • bpo-20291: Added support for variadic positional parameters in Argument Clinic.

API C

  • bpo-41710: The PyThread_acquire_lock_timed() function now clamps the timeout if it is too large, rather than aborting the process. Patch by Victor Stinner.

  • bpo-44687: BufferedReader.peek() no longer raises ValueError when the entire file has already been buffered.

  • bpo-45116: Add the Py_ALWAYS_INLINE macro to ask the compiler to always inline a static inline function. The compiler can ignore it and decides to not inline the function. Patch by Victor Stinner.

  • bpo-45094: Add the Py_NO_INLINE macro to disable inlining on a function. Patch by Victor Stinner.

  • bpo-45061: Add a deallocator to the bool type to detect refcount bugs in C extensions which call Py_DECREF(Py_True); or Py_DECREF(Py_False); by mistake. Patch by Victor Stinner.

  • bpo-42035: Add a new PyType_GetQualName() function to get type’s qualified name.

  • bpo-41103: Reverts removal of the old buffer protocol because they are part of stable ABI.

  • bpo-44751: Remove crypt.h include from the public Python.h header.

  • bpo-42747: The Py_TPFLAGS_HAVE_VERSION_TAG type flag now does nothing. The Py_TPFLAGS_HAVE_AM_SEND flag (which was added in 3.10) is removed. Both were unnecessary because it is not possible to have type objects with the relevant fields missing.

  • bpo-44530: Added the co_qualname to the PyCodeObject structure to propagate the qualified name from the compiler to code objects.

    Patch by Gabriele N. Tornetta

  • bpo-44441: Py_RunMain() now resets PyImport_Inittab to its initial value at exit. It must be possible to call PyImport_AppendInittab() or PyImport_ExtendInittab() at each Python initialization. Patch by Victor Stinner.

  • bpo-39947: Remove 4 private trashcan C API functions which were only kept for the backward compatibility of the stable ABI with Python 3.8 and older, since the trashcan API was not usable with the limited C API on Python 3.8 and older. The trashcan API was excluded from the limited C API in Python 3.9.

    Funções removidas:

    • _PyTrash_deposit_object()

    • _PyTrash_destroy_chain()

    • _PyTrash_thread_deposit_object()

    • _PyTrash_thread_destroy_chain()

    The trashcan C API was never usable with the limited C API, since old trashcan macros accessed directly PyThreadState members like _tstate->trash_delete_nesting, whereas the PyThreadState structure is opaque in the limited C API.

    Exclude also the PyTrash_UNWIND_LEVEL constant from the C API.

    Patch por Victor Stinner.

  • bpo-40939: Removed documentation for the removed PyParser_* C API.

  • bpo-43795: The list in Conteúdo da API Limitada now shows the public name PyFrameObject rather than _frame. The non-existing entry _node no longer appears in the list.

  • bpo-44378: Py_IS_TYPE() no longer uses Py_TYPE() to avoid a compiler warning: no longer cast const PyObject* to PyObject*. Patch by Victor Stinner.

  • bpo-39573: Convert the Py_TYPE() and Py_SIZE() macros to static inline functions. The Py_SET_TYPE() and Py_SET_SIZE() functions must now be used to set an object type and size. Patch by Victor Stinner.

  • bpo-44263: The PyType_Ready() function now raises an error if a type is defined with the Py_TPFLAGS_HAVE_GC flag set but has no traverse function (PyTypeObject.tp_traverse). Patch by Victor Stinner.

  • bpo-43795: The undocumented function Py_FrozenMain() is removed from the Limited API.

  • bpo-44113: Deprecate the following functions to configure the Python initialization:

    • PySys_AddWarnOptionUnicode()

    • PySys_AddWarnOption()

    • PySys_AddXOption()

    • PySys_HasWarnOptions()

    • Py_SetPath()

    • Py_SetProgramName()

    • Py_SetPythonHome()

    • Py_SetStandardStreamEncoding()

    • _Py_SetProgramFullPath()

    Use the new PyConfig API of the Python Initialization Configuration instead (PEP 587).

  • bpo-44094: Remove PyErr_SetFromErrnoWithUnicodeFilename(), PyErr_SetFromWindowsErrWithUnicodeFilename(), and PyErr_SetExcFromWindowsErrWithUnicodeFilename(). They are not documented and have been deprecated since Python 3.3.

  • bpo-43795: PyCodec_Unregister() is now properly exported as a function in the Windows Stable ABI DLL.

  • bpo-44029: Remove deprecated Py_UNICODE APIs: PyUnicode_Encode, PyUnicode_EncodeUTF7, PyUnicode_EncodeUTF8, PyUnicode_EncodeUTF16, PyUnicode_EncodeUTF32, PyUnicode_EncodeLatin1, PyUnicode_EncodeMBCS, PyUnicode_EncodeDecimal, PyUnicode_EncodeRawUnicodeEscape, PyUnicode_EncodeCharmap, PyUnicode_EncodeUnicodeEscape, PyUnicode_TransformDecimalToASCII, PyUnicode_TranslateCharmap, PyUnicodeEncodeError_Create, PyUnicodeTranslateError_Create. See PEP 393 and PEP 624 for reference.

  • bpo-42035: Add a new PyType_GetName() function to get type’s short name.

Python 3.10.0 beta 1

Data de lançamento: 2021-05-03

Segurança

  • bpo-43434: Creating sqlite3.Connection objects now also produces sqlite3.connect and sqlite3.connect/handle auditing events. Previously these events were only produced by sqlite3.connect() calls. Patch by Erlend E. Aasland.

  • bpo-43998: The ssl module sets more secure cipher suites defaults. Ciphers without forward secrecy and with SHA-1 MAC are disabled by default. Security level 2 prohibits weak RSA, DH, and ECC keys with less than 112 bits of security. SSLContext defaults to minimum protocol version TLS 1.2. Settings are based on Hynek Schlawack’s research.

  • bpo-43882: The presence of newline or tab characters in parts of a URL could allow some forms of attacks.

    Following the controlling specification for URLs defined by WHATWG urllib.parse() now removes ASCII newlines and tabs from URLs, preventing such attacks.

  • bpo-43472: Ensures interpreter-level audit hooks receive the cpython.PyInterpreterState_New event when called through the _xxsubinterpreters module.

  • bpo-43362: Fix invalid free in _sha3 module. The issue was introduced in 3.10.0a1. Python 3.9 and earlier are not affected.

  • bpo-43762: Add audit events for sqlite3.connect/handle(), sqlite3.Connection.enable_load_extension(), and sqlite3.Connection.load_extension(). Patch by Erlend E. Aasland.

  • bpo-43756: Add new audit event glob.glob/2 to incorporate the new root_dir and dir_fd arguments added to glob.glob() and glob.iglob().

  • bpo-36384: ipaddress module no longer accepts any leading zeros in IPv4 address strings. Leading zeros are ambiguous and interpreted as octal notation by some libraries. For example the legacy function socket.inet_aton() treats leading zeros as octal notation. glibc implementation of modern inet_pton() does not accept any leading zeros. For a while the ipaddress module used to accept ambiguous leading zeros.

  • bpo-43075: Fix Regular Expression Denial of Service (ReDoS) vulnerability in urllib.request.AbstractBasicAuthHandler. The ReDoS-vulnerable regex has quadratic worst-case complexity and it allows cause a denial of service when identifying crafted invalid RFCs. This ReDoS issue is on the client side and needs remote attackers to control the HTTP server.

  • bpo-42800: Audit hooks are now fired for frame.f_code, traceback.tb_frame, and generator code/frame attribute access.

  • bpo-37363: Add audit events to the http.client module.

Núcleo e embutidos

  • bpo-43977: Prevent classes being both a sequence and a mapping when pattern matching.

  • bpo-43977: Use tp_flags on the class object to determine if the subject is a sequence or mapping when pattern matching. Avoids the need to import collections.abc when pattern matching.

  • bpo-43892: Restore proper validation of complex literal value patterns when parsing match blocks.

  • bpo-43933: Set frame.f_lineno to the line number of the ‘with’ kweyword when executing the call to __exit__.

  • bpo-43933: If the current position in a frame has no line number then set the f_lineno attribute to None, instead of -1, to conform to PEP 626. This should not normally be possible, but might occur in some unusual circumstances.

  • bpo-43963: Importing the _signal module in a subinterpreter has no longer side effects.

  • bpo-42739: The internal representation of line number tables is changed to not use sentinels, and an explicit length parameter is added to the out of process API function PyLineTable_InitAddressRange. This makes the handling of line number tables more robust in some circumstances.

Biblioteca

Núcleo e embutidos

  • bpo-43901: Change class and module objects to lazy-create empty annotations dicts on demand. The annotations dicts are stored in the object’s __dict__ for backwards compatibility.

  • bpo-43892: Match patterns now use new dedicated AST nodes (MatchValue, MatchSingleton, MatchSequence, MatchStar, MatchMapping, MatchClass) rather than reusing expression AST nodes. MatchAs and MatchOr are now defined as pattern nodes rather than as expression nodes. Patch by Nick Coghlan.

  • bpo-42725: Usage of await/yield/yield from and named expressions within an annotation is now forbidden when PEP 563 is activated.

  • bpo-43754: When performing structural pattern matching (PEP 634), captured names are now left unbound until the entire pattern has matched successfully.

  • bpo-42737: Annotations for complex targets (everything beside simple names) no longer cause any runtime effects with from __future__ import annotations.

  • bpo-43914: SyntaxError exceptions raised by the interpreter will highlight the full error range of the expression that constitutes the syntax error itself, instead of just where the problem is detected. Patch by Pablo Galindo.

  • bpo-38605: Revert making from __future__ import annotations the default. This follows the Steering Council decision to postpone PEP 563 changes to at least Python 3.11. See the original email for more information regarding the decision: https://mail.python.org/archives/list/python-dev@python.org/thread/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/. Patch by Pablo Galindo.

  • bpo-43475: Hashes of NaN values now depend on object identity. Formerly, they always hashed to 0 even though NaN values are not equal to one another. Having the same hash for unequal values caused pile-ups in hash tables.

  • bpo-43859: Improve the error message for IndentationError exceptions. Patch by Pablo Galindo

  • bpo-41323: Constant tuple folding in bytecode optimizer now reuses tuple in constant table.

  • bpo-43846: Data stack usage is much reduced for large literal and call expressions.

  • bpo-38530: When printing NameError raised by the interpreter, PyErr_Display() will offer suggestions of similar variable names in the function that the exception was raised from. Patch by Pablo Galindo

  • bpo-43823: Improve syntax errors for invalid dictionary literals. Patch by Pablo Galindo.

  • bpo-43822: Improve syntax errors in the parser for missing commas between expressions. Patch by Pablo Galindo.

  • bpo-43798: ast.alias nodes now include source location metadata attributes e.g. lineno, col_offset.

  • bpo-43797: Improve SyntaxError error messages for invalid comparisons. Patch by Pablo Galindo.

  • bpo-43760: Move the flag for checking whether tracing is enabled to the C stack, from the heap. Should speed up dispatch in the interpreter.

  • bpo-43682: Static methods (@staticmethod) and class methods (@classmethod) now inherit the method attributes (__module__, __name__, __qualname__, __doc__, __annotations__) and have a new __wrapped__ attribute. Patch by Victor Stinner.

  • bpo-43751: Fixed a bug where anext(ait, default) would erroneously return None.

  • bpo-42128: __match_args__ is no longer allowed to be a list.

  • bpo-43683: Add GEN_START opcode. Marks start of generator, including async, or coroutine and handles sending values to a newly created generator or coroutine.

Biblioteca

  • bpo-43105: Importlib now resolves relative paths when creating module spec objects from file locations.

Núcleo e embutidos

  • bpo-43682: Static methods (@staticmethod) are now callable as regular functions. Patch by Victor Stinner.

  • bpo-42609: Prevented crashes in the AST validator and optimizer when compiling some absurdly long expressions like "+0"*1000000. RecursionError is now raised instead.

  • bpo-38530: When printing AttributeError, PyErr_Display() will offer suggestions of similar attribute names in the object that the exception was raised from. Patch by Pablo Galindo

Biblioteca

  • bpo-44015: In @dataclass(), raise a TypeError if KW_ONLY is specified more than once.

  • bpo-25478: Added a total() method to collections.Counter() to compute the sum of the counts.

  • bpo-43733: Change netrc.netrc to use UTF-8 encoding before using locale encoding.

  • bpo-43979: Removed an unnecessary list comprehension before looping from urllib.parse.parse_qsl(). Patch by Christoph Zwerschke and Donghee Na.

  • bpo-43993: Update bundled pip to 21.1.1.

  • bpo-43957: [Enum] Deprecate TypeError when non-member is used in a containment check; In 3.12 True or False will be returned instead, and containment will return True if the value is either a member of that enum or one of its members’ value.

  • bpo-42904: For backwards compatibility with previous minor versions of Python, if typing.get_type_hints() receives no namespace dictionary arguments, typing.get_type_hints() will search through the global then local namespaces during evaluation of stringized type annotations (string forward references) inside a class.

  • bpo-43945: [Enum] Deprecate non-standard mixin format() behavior: in 3.12 the enum member, not the member’s value, will be used for format() calls.

  • bpo-41139: Deprecate undocumented cgi.log() API.

  • bpo-43937: Fixed the turtle module working with non-default root window.

  • bpo-43930: Update bundled pip to 21.1 and setuptools to 56.0.0

  • bpo-43907: Fix a bug in the pure-Python pickle implementation when using protocol 5, where bytearray instances that occur several time in the pickled object graph would incorrectly unpickle into repeated copies of the bytearray object.

  • bpo-43926: In importlib.metadata, provide a uniform interface to Description, allow for any field to be encoded with multiline values, remove continuation lines from multiline values, and add a .json property for easy access to the PEP 566 JSON-compatible form. Sync with importlib_metadata 4.0.

  • bpo-43920: OpenSSL 3.0.0: load_verify_locations() now returns a consistent error message when cadata contains no valid certificate.

  • bpo-43607: urllib can now convert Windows paths with \\?\ prefixes into URL paths.

  • bpo-43817: Add inspect.get_annotations(), which safely computes the annotations defined on an object. It works around the quirks of accessing the annotations from various types of objects, and makes very few assumptions about the object passed in. inspect.get_annotations() can also correctly un-stringize stringized annotations.

    inspect.signature(), inspect.from_callable(), and inspect.from_function() now call inspect.get_annotations() to retrieve annotations. This means inspect.signature() and inspect.from_callable() can now un-stringize stringized annotations, too.

  • bpo-43284: platform.win32_ver derives the windows version from sys.getwindowsversion().platform_version which in turn derives the version from kernel32.dll (which can be of a different version than Windows itself). Therefore change the platform.win32_ver to determine the version using the platform module’s _syscmd_ver private function to return an accurate version.

  • bpo-42854: The ssl module now uses SSL_read_ex and SSL_write_ex internally. The functions support reading and writing of data larger than 2 GB. Writing zero-length data no longer fails with a protocol violation error.

  • bpo-42333: Port _ssl extension module to multiphase initialization.

  • bpo-43880: ssl now raises DeprecationWarning for OP_NO_SSL/TLS* options, old TLS versions, old protocols, and other features that have been deprecated since Python 3.6, 3.7, or OpenSSL 1.1.0.

  • bpo-41559: PEP 612 is now implemented purely in Python; builtin types.GenericAlias objects no longer include typing.ParamSpec in __parameters__ (with the exception of collections.abc.Callable‘s GenericAlias). This means previously invalid uses of ParamSpec (such as list[P]) which worked in earlier versions of Python 3.10 alpha, will now raise TypeError during substitution.

  • bpo-43867: The