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)
---
name: python-knowledge-patch
description: Python
version: "3.15.2"
license: MIT
metadata:
author: Nevaberry
---
# Python compatibility guidance
Load this skill when updating Python applications, tooling, source builds, or C
extensions. Use the topic references for complete details and version-specific
conditions; the quick reference starts with compatibility changes.
> [!CAUTION]
> Guidance marked prerelease may change before stable release.
## Topic index
| Reference | Topics |
| --- | --- |
| [Build and distribution](references/build-and-distribution.md) | Installers, signatures, JIT, dependencies, build metadata, virtual environments |
| [C API and extensions](references/c-api-and-extensions.md) | ABI targets, embedding, ownership, argument parsing, writers, ctypes |
| [Concurrency and asyncio](references/concurrency-and-asyncio.md) | Tasks, cancellation, servers, threads, context, multiprocessing |
| [Data, I/O, and serialization](references/data-io-and-serialization.md) | Containers, encodings, streams, archives, JSON, TOML, XML, dates, SQLite |
| [Filesystems, operating systems, and platforms](references/filesystem-os-and-platforms.md) | Paths, permissions, processes, Windows encodings, Tkinter |
| [Language and runtime](references/language-and-runtime.md) | Imports, startup, resources, syntax, flags, garbage collection |
| [Networking and security](references/networking-and-security.md) | URLs, HTTP, email, cookies, TLS, IP addresses |
| [Tooling, debugging, and testing](references/tooling-debugging-and-testing.md) | CLI parsing, debugging, profiling, warnings, logging, tests |
| [Typing and introspection](references/typing-and-introspection.md) | Annotations, signatures, type relationships, ASTs, symbols, runtime inspection |
## Breaking changes and deprecations
### 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__`.
### Resource anchors
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
`importlib.resources.files()` drops the deprecated `package=` keyword. Pass the
anchor positionally or use `files(anchor='mypackage')`.
### AST 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.
### Code object line tables
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
`code.co_lnotab` was removed. Use `code.co_lines()` to iterate over bytecode offset
ranges and their source line numbers.
### Iterator serialization
`itertools` iterators no longer support `copy.copy()`, `copy.deepcopy()`, or
pickling. To resume iteration after serialization, save the input and progress
separately so the iterator can be reconstructed.
### 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.
### Date formats without a year
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')`.
### UTF-8 defaults
> **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.
### Path errors and recursive matching
`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. In `Path.glob()` and `Path.rglob()`, a pattern ending in `**`
now matches files as well as directories; use `root.glob("**/")` for directory-only
results. Exceptions other than `OSError` subclasses propagate from
`shutil.rmtree()` even with `ignore_errors=True`.
### Runtime checks on derived protocols
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
Apply `@typing.runtime_checkable` directly to a derived protocol used in
`isinstance()` or `issubclass()`. Relying on the decorator from a parent protocol
is deprecated and will raise `TypeError` in Python 3.20.
### ctypes structure layout
On non-Windows platforms, using `_pack_` alone to request the Microsoft layout
is deprecated. Set `_layout_ = "ms"` before assigning `_fields_` when the structure
must match the Microsoft ABI. Passing a string to `ctypes.POINTER()` is deprecated;
define the structure first, then assign `_fields_` using the class itself for any
self-referential pointer.
### C API replacements and ownership
The Limited API drops `PySequence_Fast_GET_SIZE`, `PySequence_Fast_GET_ITEM`, and
`PySequence_Fast_ITEMS`. Use public operations such as `PySequence_Size()` and
`PySequence_GetItem()`, accounting for the new reference returned by the latter.
`PyModule_Add(module, name, value)` consumes the caller's reference even on failure.
`PyObject_GetBuffer()` and `PyBuffer_FillInfo()` raise `SystemError` for
`PyBUF_READ` and `PyBUF_WRITE`; reserve those flags for memoryview APIs and use
`PyBUF_WRITABLE` when requesting a writable buffer.
## Imports, data, and annotations
### Explicit lazy imports
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
Use `lazy import json` or `lazy from decimal import Decimal` at module scope to
defer loading until first use. Set `PYTHON_LAZY_IMPORTS=all` for automatic lazy
imports. `sys.lazy_modules` is a set, and beta 3 removes the `none` mode.
### Selective lazy imports
Set `__lazy_modules__` to a container of fully qualified module names to defer
regular imports and their errors until first use. A callback passed to
`sys.set_lazy_imports_filter()` receives `(importing, imported, fromlist)` and
returns `False` for imports that must load eagerly.
### Frozen mappings and JSON arrays
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
Use `frozendict({"region": "eu"})` for an immutable mapping that can be hashed when
its keys and values are hashable. Pass `array_hook` to `json.load()` or
`json.loads()` to transform each decoded array. For example,
`json.loads('[{"ids": [1, 2]}]', array_hook=tuple, object_pairs_hook=frozendict)`
produces nested tuples and frozen mappings.
### Unresolved annotations and typed dictionary keys
Use `inspect.signature(func, annotation_format=annotationlib.Format.FORWARDREF)`
to retain unresolved annotations as forward references. With `Format.STRING`,
call `sig.format(unquote_annotations=True)` to display annotation text without
surrounding quotes. For typed dictionaries, use `closed=True` to forbid
undeclared keys, or specify `extra_items` to give undeclared keys a value type.
## Async tasks and thread context
### Custom task factories
In Python 3.14, `asyncio.create_task()`, `loop.create_task()`, and
`TaskGroup.create_task()` forward keyword arguments to the task constructor or
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`. See the concurrency reference
for the different factory contracts across 3.13 releases.
### Task-group cancellation
When an externally cancelled `asyncio.TaskGroup` also has to raise an
`ExceptionGroup`, it reissues cancellation on the parent task so the next `await`
can deliver `CancelledError`. Task groups preserve `Task.cancelling()`, and
`Task.uncancel()` can rescind an undelivered cancellation when the count reaches zero.
### Explicit group cancellation
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
Call `group.cancel()` inside an `asyncio.TaskGroup` to cancel its unfinished tasks
and exit the group without propagating a `CancelledError` from that cancellation.
### Server closure
`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()`.
### Context inheritance and warning filters
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
behavior needs to be independent of `-X thread_inherit_context`.
`warnings.catch_warnings()` stores filters in a context variable when
`sys.flags.context_aware_warnings` is true. 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`.
## Profiling and native extensions
### Deterministic profiling
`profiling.tracing` contains the deterministic profiler and `cProfile` remains
an alias. Migrate from `profile` to `profiling.tracing` before `profile` is
removed in 3.17.
### Sampling captures
> **Prerelease (`3.15.0b3`):** This guidance may change before stable release.
Use `python -m profiling.sampling` to sample Python processes. Use `--subprocesses`
for separate profiles of spawned Python processes, `--live` for an interactive
view, `--jsonl` for line-delimited data, or `--binary` for a capture to `replay`.
### Sampling format compatibility
> **Prerelease (`changelog-3-15`):** This guidance may change before stable release.
Beta 4 changed the binary profile format; recreate captures from earlier
prereleases for replay on later builds. For async-aware capture, use
`--gecko --async-aware` because `--binary` rejects `--async-aware`.
### Free-threaded C iteration and ABI targets
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.
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`.