Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Python Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-python-knowledge-patch-nevaberry-plugins)
---
name: python-knowledge-patch
description: Python
version: "3.15.2"
license: MIT
metadata:
author: Nevaberry
---
# Python knowledge patch
Load this skill when updating Python applications, libraries, tools, builds,
or C extensions. Use the quick reference for compatibility changes and the
topic files for complete guidance, examples, and version-specific behavior.
> [!CAUTION]
> Guidance explicitly marked prerelease may change before stable release.
> Preserve the item-level attribution when applying that guidance.
## Reference index
| Reference | Topics |
| --- | --- |
| [Build and distribution](references/build-and-distribution.md) | Installers, signatures, JIT, dependencies, compiler options, virtual environments, build metadata |
| [C API and extensions](references/c-api-and-extensions.md) | ABI selection, module exports, type slots, ownership, buffers, embedding, ctypes |
| [Concurrency and asyncio](references/concurrency-and-asyncio.md) | Task factories, cancellation, servers, transports, thread contexts, processes |
| [Data, I/O, and serialization](references/data-io-and-serialization.md) | Text I/O, mappings, JSON, pickle, marshal, archives, encodings, dates, XML, databases |
| [Filesystems, operating systems, and platforms](references/filesystem-os-and-platforms.md) | Paths, permissions, symlinks, environment, memory maps, locale, Windows, Tkinter |
| [Language and runtime](references/language-and-runtime.md) | Imports, startup files, resources, comprehensions, warnings, execution states, collection |
| [Networking and security](references/networking-and-security.md) | Email, IMAP, URLs, HTTP, cookies, TLS |
| [Tooling, debugging, and testing](references/tooling-debugging-and-testing.md) | Debuggers, profilers, logging, unittest, monitoring, command-line parsing |
| [Typing and introspection](references/typing-and-introspection.md) | AST construction, annotations, signatures, type forms, typed dictionaries, protocols |
## Breaking changes and deprecations
### Legacy import loaders
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
The import system and its loaders drop `load_module()`. Custom loaders should implement `exec_module()` and use the module spec for import metadata. Read the cached bytecode path from `module.__spec__.cached` because import no longer sets `module.__cached__`.
### UTF-8 mode by default
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
Python now enables UTF-8 mode by default. Pass an explicit `encoding=` to text I/O that reads or writes a legacy locale encoding.
### AST constructor validation
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
AST constructors now raise `TypeError` when you omit a required field or supply an unknown keyword. Instantiating abstract nodes such as `ast.expr` is deprecated for removal in 3.20.
### SQLite calling conventions
`sqlite3.connect()` takes every argument after `database` by keyword, as in `sqlite3.connect(path, timeout=10)`. Pass the first three arguments to `create_function()` and `create_aggregate()` positionally, and pass the leading argument to `set_authorizer()`, `set_progress_handler()`, and `set_trace_callback()` positionally.
### Years in `strptime()` formats
A format containing `%d` without a year directive now raises `ValueError`. When parsing a stand-alone month and day, supply a reference year that allows February 29, as in `datetime.strptime('02/29/2000', '%m/%d/%Y')`.
### Copying and pickling itertools iterators
`itertools` iterators no longer support `copy.copy()`, `copy.deepcopy()`, or pickling. If you need to resume iteration after serialization, save the input and progress separately so the iterator can be reconstructed.
### Path probing errors
`Path.exists()` and the file-type predicates now return `False` for any `OSError`. Use `Path.stat()` when callers need to distinguish a missing path from an access failure.
### Fast sequence macros in the Limited API
The Limited API drops `PySequence_Fast_GET_SIZE`, `PySequence_Fast_GET_ITEM`, and `PySequence_Fast_ITEMS`. Use public sequence operations such as `PySequence_Size()` and `PySequence_GetItem()`, and account for the new reference returned by `PySequence_GetItem()`.
## Package startup and lazy imports
### Migrating executable `.pth` lines
Put a no-argument entry point such as `mypkg.startup:initialize` in `mypkg.start`. A matching `.start` file suppresses executable `import` lines in `mypkg.pth` while the path entries still extend `sys.path`.
### Selective lazy imports
Set `__lazy_modules__` to a container of fully qualified module names to defer regular imports and their errors until first use. Call `sys.set_lazy_imports_filter()` with a callback `(importing, imported, fromlist)` that returns `False` for imports that must load eagerly.
```python
__lazy_modules__ = {"json"}
import json
```
## Async shutdown, task creation, and thread contexts
### Async server shutdown
`asyncio.Server.wait_closed()` waits for the server to close and its active connections to finish. Call `server.close()` first to stop accepting connections, then use `server.close_clients()` for graceful client closure or `server.abort_clients()` for immediate closure before awaiting `server.wait_closed()`.
### Asyncio task factory keyword arguments
`asyncio.create_task()`, `loop.create_task()`, and `TaskGroup.create_task()` forward keyword arguments to the task constructor or the custom factory, including `name` and `context`. A factory can accept `(loop, coro, **kwargs)` and return `asyncio.Task(coro, loop=loop, **kwargs)` to preserve those options, including `context=None`.
### Thread context inheritance
On free-threaded builds, a new `threading.Thread` defaults to a copy of the context of the caller of `start()`. Other builds default to an empty context. Pass `context=contextvars.Context()` or `context=contextvars.copy_context()` when the behavior needs to be independent of `-X thread_inherit_context`.
### Context-local warning filters
`warnings.catch_warnings()` stores filters in a context variable when `sys.flags.context_aware_warnings` is true, so concurrent uses can have independent filters. The flag defaults to true on free-threaded builds and false on other builds. Enable it at startup with `python -X context_aware_warnings=1 app.py`.
## Annotations and typed dictionaries
### Annotations in metaclasses
Use `annotationlib.get_annotate_from_class_namespace(namespace)` to retrieve the annotation function from the namespace passed to a metaclass before the class exists. This helper supersedes the earlier `annotationlib.get_annotate_function()` name.
### Forward-reference reevaluation
`annotationlib.ForwardRef.evaluate()` reevaluates the reference on each call, so a change in the namespace can change the result. Pass `format=annotationlib.Format.FORWARDREF` to preserve references that are still unresolved.
### Annotation formats in function signatures
Use `inspect.signature(func, annotation_format=annotationlib.Format.FORWARDREF)` to inspect a signature while retaining unresolved annotations as forward references. With `Format.STRING`, call `sig.format(unquote_annotations=True)` to display the annotation text without surrounding quotes.
### Typed dictionaries with explicit extra-key policies
Use `closed=True` to forbid undeclared keys, or specify `extra_items` to give undeclared keys a value type.
```python
from typing import TypedDict
class Metrics(TypedDict, extra_items=float):
name: str
```
## Paths, buffers, and encoding controls
### Cached path type queries
`Path.info` caches file type queries and can already hold directory scan information on paths returned by `iterdir()`. Call `path.is_dir()` or `path.is_file()` directly when a fresh check matters.
### Permissions for intermediate directories
`os.makedirs()` and `Path.mkdir(parents=True)` accept `parent_mode=` for directories created along the way. For example, `Path('cache/reports').mkdir(mode=0o700, parents=True, parent_mode=0o750)` requests different modes for `reports` and a newly created `cache`.
### Taking bytes out of a `bytearray`
`buf.take_bytes()` consumes the entire buffer as `bytes`. Pass a positional count to consume a prefix and leave the rest in the buffer.
```python
buf = bytearray(b"abc\ndef")
assert buf.take_bytes(4) == b"abc\n"
assert buf == bytearray(b"def")
```
### Base encoding controls
Use `padded=` on `b32encode()`, `b32decode()` and their `b32hex` counterparts, or on `b64encode()` and `b64decode()`. The decoders also take `canonical=True` to reject noncanonical input, as in `base64.b32decode(b'ME', padded=False, canonical=True)`.
## Profiling and TLS configuration
### Sampling profiler CLI
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
Use `python -m profiling.sampling` to sample Python processes. The `dump` subcommand takes one stack snapshot. Use `--subprocesses` to collect separate profiles for spawned Python processes, `--live` for an interactive view, `--jsonl` for line-delimited data, or `--binary` to save a capture for the `replay` subcommand.
### Sampling profiler binary compatibility
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
Beta 4 changed the binary profile format, so recreate captures made with earlier prereleases for replay on later builds. For async-aware capture, use `--gecko --async-aware` because `--binary` rejects `--async-aware`.
### TLS negotiation settings
Use `SSLContext.set_ciphersuites()` for TLS 1.3 and `SSLContext.set_ciphers()` for TLS 1.2 and earlier. Use `SSLContext.set_groups()` to configure multiple key-agreement groups and key shares, `SSLContext.get_groups()` to list available groups for the configured TLS versions with OpenSSL 3.5 or later, and `SSLSocket.group()` to inspect the negotiated group with OpenSSL 3.2 or later.
## C extension ownership and free-threaded builds
### Module attribute ownership in C
`PyModule_Add(module, name, value)` consumes the caller’s reference to `value` even when the call fails.
### Free-threaded C dictionary iteration
Hold a dictionary's critical section from `Py_BEGIN_CRITICAL_SECTION(dict)` through `Py_END_CRITICAL_SECTION()` around the entire `PyDict_Next()` loop on a free-threaded build. Acquire strong references to keys or values before releasing the section if they need to outlive it.
### Targeting the free-threaded Stable ABI
To target `abi3t` directly, set `Py_TARGET_ABI3T`, use a `PyModExport_*` entry point, and migrate extension instance storage to the type-data API using a negative `basicsize` and `PyObject_GetTypeData()`. Build a separate `cp315t` extension if the extension or its build tooling cannot target `abi3t`.