pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Add bindings for new PyUnstable APIs in 3.14

Open ngoldbaum opened this issue 3 months ago • 1 comments

There are a few new C API additions in 3.14 that I think will help supporting the free-threaded build:

  • PyUnstable_Object_IsUniquelyReferenced

    Replaces uses of Py_REFCNT(obj) == 1. This is needed for certain optimizations and it'd be nice to be able to do those optimizations safely on the free-threaded build.

  • PyUnstable_Object_IsUniquelyReferencedTemporary

    More niche, used to detect uniquely referenced temporaries created by certain Python bytecode operations. NumPy uses this along with some code to scan the call stack to elide temporaries that are created by NumPy internals or by Python bytecode. It's pretty cursed. There are probably less cursed ways to use this.

  • PyUnstable_EnableTryIncref and PyUnstable_TryIncref

    See the docs for PyUnstable_TryIncRef. This is needed in some advanced cases to properly handle weak references without lots of overhead. I think there are other cases as well.

ngoldbaum avatar Sep 01 '25 14:09 ngoldbaum

I created a C backport for IsUniquelyReferenced, see: https://github.com/python/pythoncapi-compat/pull/149

That might be useful for inspiration if anyone wants to write a safe wrapper that works on older Python versions.

ngoldbaum avatar Sep 01 '25 16:09 ngoldbaum