Rate this Page
★ ★ ★ ★ ★

Python Object Interop#

Include <torch/csrc/stable/pyobject.h> to convert between Python objects and stable C++ values without including Python.h in the extension’s public headers. You may be interested in these conversions if you’d like to bypass the torch dispatcher when binding ops to Python. Similar to all stable header usage, configure TORCH_TARGET_VERSION for the oldest runtime you intend to support.

Your extension can link only libtorch, but in order to use these APIs, please ensure libtorch_python is loaded at runtime. When calling any of the Python conversion functions below, the caller must hold the GIL.

Without an explicit target, the build version is used. Each group below requires both a target and runtime at least as new as its stated minimum.

Tensor Conversions#

Minimum target and runtime: PyTorch 2.14.

inline Tensor torch::stable::tensor_from_pyobject(void *py_obj)#

Borrow a non-null Python torch.Tensor or actual subclass; overridden __class__ attributes do not affect the type check.

The returned stable Tensor owns a native handle sharing TensorImpl, without copying tensor data.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.14 or newer.

Parameters:

py_obj – Borrowed PyObject* passed as void*, kept alive for the call.

Returns:

An owning stable Tensor sharing the input tensor state.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::tensor_to_pyobject(const Tensor &t, void *py_type = nullptr)#

Return an owning Python reference sharing the native tensor state.

An existing Python wrapper may be reused; a new reference does not imply a new allocation. A requested type must be a Tensor subclass, and a cached wrapper must be compatible with it. The default route uses the runtime default tensor wrapper type.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.14 or newer.

Parameters:
  • t – Borrowed stable Tensor, kept alive for the call.

  • py_type – Optional borrowed PyTypeObject* passed as void*; nullptr selects the default route.

Returns:

A new owning PyObject* reference passed as void*. An undefined native tensor maps to Python None. Release or transfer the reference through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

Tensor Probe, Dtypes and Devices#

Minimum target and runtime: PyTorch 2.15.

inline bool torch::stable::is_tensor_pyobject(void *py_obj)#

Check the actual Python type against torch.Tensor or its subclasses; overridden __class__ attributes are ignored.

Non-tensors return false, but a null pointer or missing Python backend is an error, not false.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.15 or newer.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*, kept alive for the call.

Returns:

Whether the actual object type is a Tensor or subclass.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline torch::headeronly::ScalarType torch::stable::dtype_from_pyobject(void *py_obj)#

Require an actual torch.dtype.

The stable runtime enum mapping covers only supported ScalarTypes, so a valid Python dtype outside that subset fails. The by-value result retains no Python storage.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.15 or newer.

Parameters:

py_obj – Borrowed, non-null Python dtype object passed as void*.

Returns:

A ScalarType value translated through the runtime stable mapping.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::dtype_to_pyobject(torch::headeronly::ScalarType dtype)#

Translate a supported ScalarType through the runtime stable enum mapping and acquire a reference to the registered Python dtype singleton; no extension enum encoding is frozen by this conversion.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.15 or newer.

Parameters:

dtype – ScalarType supported by the stable mapping.

Returns:

A new owning reference to the dtype singleton, passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline Device torch::stable::device_from_pyobject(void *py_obj)#

Require an actual torch.device.

DeviceType uses the supported runtime stable mapping; valid devices outside its subset fail. The device index is preserved, including -1 for an unspecified index; no Python input storage is retained.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.15 or newer.

Parameters:

py_obj – Borrowed, non-null Python device object passed as void*.

Returns:

An independent stable Device value with the mapped type and index.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::device_to_pyobject(const Device &device)#

Translate the DeviceType through the supported runtime stable mapping and construct a Python device with the same index.

The result does not borrow the C++ Device or its storage.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.15 or newer.

Parameters:

device – Borrowed stable Device, kept alive for the call.

Returns:

A new owning Python device reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

Layout and Memory Format#

Minimum target and runtime: PyTorch 2.16.

inline torch::headeronly::Layout torch::stable::layout_from_pyobject(void *py_obj)#

Require an actual torch.layout and translate its runtime code through the stable Layout mapping.

All currently exposed torch.layout values are supported; the result retains no Python storage.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null Python layout object passed as void*.

Returns:

A by-value Layout selected through the runtime mapping.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::layout_to_pyobject(torch::headeronly::Layout layout)#

Translate Layout through the runtime stable mapping and acquire a reference to the registered Python layout singleton; it does not allocate a duplicate singleton.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

layout – Layout value supported by the stable mapping.

Returns:

A new owning layout reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline torch::headeronly::MemoryFormat torch::stable::memory_format_from_pyobject(void *py_obj)#

Require an actual torch.memory_format and translate its runtime code through the stable mapping.

The supported formats are contiguous, preserve, channels-last and channels-last-3d; the result retains no Python storage.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null Python memory-format object passed as void*.

Returns:

An independent by-value MemoryFormat selected through the runtime mapping.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::memory_format_to_pyobject(torch::headeronly::MemoryFormat memory_format)#

Translate MemoryFormat through the runtime stable mapping and acquire a reference to the registered singleton; no C++ input storage is retained.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

memory_format – Contiguous, preserve, channels-last or channels-last-3d format.

Returns:

A new owning memory-format reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

Scalars#

Minimum target and runtime: PyTorch 2.16.

inline bool torch::stable::bool_from_pyobject(void *py_obj)#

Read a Python bool (PyObject* passed as void*).

Only True and False are accepted; NumPy booleans and general truthiness conversions are rejected.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*, kept alive for the call.

Returns:

The bool value, with no retained Python reference.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::bool_to_pyobject(bool value)#

Return a reference to the Python bool singleton for value; no new bool allocation is implied.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

value – Bool value to convert.

Returns:

A new owning Python bool reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline int64_t torch::stable::int64_from_pyobject(void *py_obj)#

Read a Python int or subclass (PyObject* passed as void*) as an int64_t.

NumPy integer scalars are also accepted when runtime NumPy support is available and unpacking succeeds. bool and values outside the int64_t range are rejected; an unrelated __index__ method alone does not pass the type gate.

Note

Conversion failures throw. CPython failures additionally remain pending, and their diagnostic is available to a handling C++ caller.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*, kept alive for the call.

Returns:

The checked int64_t value, with no retained Python reference.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::int64_to_pyobject(int64_t value)#

Convert the full int64_t value into a Python integer; the result does not borrow native input storage.

Note

Allocation/conversion failures throw; a CPython error remains pending.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

value – Integer value to convert.

Returns:

A new owning Python int reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline double torch::stable::double_from_pyobject(void *py_obj)#

Read a Python float, int or subclass (PyObject* passed as void*) as a double, including bool (True becomes 1.0).

With runtime NumPy support, NumPy boolean, integer, floating and complex scalars are accepted if float conversion succeeds. NumPy complex conversion discards the imaginary part and can emit ComplexWarning; promoting that warning to an exception makes conversion fail. This uses PythonArgParser’s builtin/NumPy scalar check-and-unpack policy, not its Tensor or symbolic-number conveniences. Builtin complex and unrelated objects with only __float__ or __index__ methods are rejected.

Note

Conversion failures throw. CPython failures additionally remain pending, and their diagnostic is available to a handling C++ caller.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*, kept alive for the call.

Returns:

A double value, preserving signed zero, infinities and NaN without retaining the input.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::double_to_pyobject(double value)#

Convert the double value into a Python float; the result does not borrow native input storage.

Note

Allocation/conversion failures throw; a CPython error remains pending.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

value – Double value to convert.

Returns:

A new owning Python float reference passed as void*. Release or transfer it through Python APIs.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

Strings#

Minimum target and runtime: PyTorch 2.16.

inline std::string torch::stable::string_from_pyobject(void *py_obj)#

Copy a Python string or bytes object into an owned std::string.

Python str and bytes objects, including subclasses, are accepted without coercing other objects with str(). A str is encoded as strict UTF-8; bytes are copied as-is, including invalid UTF-8. Explicit lengths preserve embedded NUL bytes. A str containing a lone surrogate, such as the Python literal

"\ud800"
cannot be encoded as UTF-8 and fails with UnicodeEncodeError pending.

The runtime copies the bytes into an owning StringHandle. This wrapper copies the handle’s bytes into std::string and releases the handle on success or exceptional exit; neither the result nor the handle borrows Python storage. Conversion failures throw a C++ exception; CPython errors remain pending.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*. The caller keeps it alive for the call.

Returns:

An owning std::string, independent of the input object’s lifetime.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::string_to_pyobject(std::string_view str)#

Decode a borrowed UTF-8 byte range into an owned Python str.

The view’s pointer and length are borrowed only for this call. CPython copies and decodes the bytes into Python-owned Unicode storage; the result does not retain the view or its buffer. Embedded NUL bytes are preserved. Invalid UTF-8 fails with UnicodeDecodeError pending, and conversion failures throw a C++ exception. No temporary std::string is needed for this output conversion.

Note

Requires a TORCH_TARGET_VERSION and runtime of PyTorch 2.16 or newer.

Parameters:

str – Borrowed UTF-8 bytes. The caller keeps the buffer alive for the call. A null data pointer is allowed only when the size is zero, as with a default-constructed empty std::string_view; nonempty views must be non-null.

Returns:

A new owning reference to Python str, passed as void*. The caller releases or transfers it through the appropriate Python reference API.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

Generators#

Minimum target and runtime: PyTorch 2.16.

inline Generator torch::stable::generator_from_pyobject(void *py_obj)#

Convert a Python torch.Generator (or subclass) to an owning stable Generator.

Minimum compatible version: PyTorch 2.16. Build time minimum version: PyTorch 2.16.

Parameters:

py_obj – Borrowed, non-null PyObject* passed as void*. The caller keeps it alive for the call.

Returns:

An owning Generator that shares the input’s RNG state and keeps its Python wrapper alive; the RNG state is not cloned.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.

inline void *torch::stable::generator_to_pyobject(const Generator &generator)#

Convert a defined stable Generator to a new-reference Python torch.Generator.

The result shares the RNG state and reuses the GeneratorImpl’s existing Python wrapper, including its subclass, when one exists.

Minimum compatible version: PyTorch 2.16. Build time minimum version: PyTorch 2.16.

Parameters:

generator – Borrowed for the call. Its underlying handle must be non-null and represent a defined Generator; it remains usable after conversion.

Returns:

A new owning Python reference, passed as void*. The caller releases or transfers it through the appropriate Python reference API.

Pre:

The caller holds the GIL and libtorch_python is loaded at runtime.