Appendix

C++

<libpy/abi.h>

struct abi_version

Structure for holding the ABI version of the libpy library.

Note

This must match libpy.load_library._abi_verson in the Python support library.

abi_version py::abi::libpy_abi_version

The version of the libpy shared object.

bool py::abi::compatible_versions(abi_version provider, abi_version consumer)

Check if two abi versions are compatible.

Parameters
  • provider: The version of the implementation provider.

  • consumer: The version of the implementation consumer.

bool py::abi::ensure_compatible_libpy_abi()

Check that the ABI of the libpy object is compatible with an extension module compiled against libpy.

Return

true with a Python exception raised if the ABI versions are incompatible.

<libpy/any.h>

class py::any_vtable

A collection of operations and metadata about a type to implement type-erased containers.

The constructor is private, use py::any_vtable::make<T>() to look up the vtable for a given type.

Public Functions

constexpr any_vtable()
constexpr const detail::any_vtable_impl *impl() const

Get access to the underlying collection of function pointers.

constexpr const std::type_info &type_info() const
constexpr std::size_t size() const
constexpr std::size_t align() const
constexpr bool is_trivially_default_constructible() const
constexpr bool is_trivially_destructible() const
constexpr bool is_trivially_move_constructible() const
constexpr bool is_trivially_copy_constructible() const
constexpr bool is_trivially_copyable() const
void copy_assign(void *lhs, const void *rhs) const
void move_assign(void *lhs, void *rhs) const
void default_construct(void *dest) const
void copy_construct(void *dest, const void *value) const
void move_construct(void *dest, void *value) const
void destruct(void *dest) const
bool move_is_noexcept() const
void move_if_noexcept(void *dest, void *value) const
bool ne(const void *lhs, const void *rhs) const
bool eq(const void *lhs, const void *rhs) const
owned_ref to_object(const void *addr) const
owned_ref<PyArray_Descr> new_dtype() const
std::ostream &ostream_format(std::ostream &stream, const void *addr) const
std::string type_name() const
std::byte *alloc(std::size_t count) const

Allocate uninitialized memory for count objects of the given type.

std::byte *default_construct_alloc(std::size_t count) const

Allocate memory and default construct count objects of the given type.

void free(std::byte *addr) const

Free memory allocated with alloc or default_construct_alloc.

constexpr bool operator==(const any_vtable &other) const

Check if this vtable refers to the same type as another vtable.

constexpr bool operator!=(const any_vtable &other) const

Check if this vtable does not refer to the same type as another vtable.

Public Static Functions

template<typename T>
constexpr any_vtable make()
class py::any_ref

A mutable dynamic reference to a value whose type isn’t known until runtime.

This object is like std::any, except it is non-owning. Assignment has reference semantics, meaning it will assign through to the referent.

See

make_any_ref

Public Functions

any_ref(void *addr, const any_vtable &vtable)

Construct an any_ref from some arbitrary address and an assignment function. The assignment function pointer doubles as the run time type tag.

Parameters
  • addr: The address of the referent.

  • vtable: The vtable for the type of the referent.

any_ref(const any_ref &cpfrom)
any_ref &operator=(const any_ref &rhs)
any_ref &operator=(const any_cref &rhs)
template<typename T>
any_ref &operator=(const T &rhs)
template<typename T>
bool operator!=(const T &rhs) const
template<typename T>
bool operator==(const T &rhs) const
const any_vtable &vtable() const
template<typename T>
T &cast()

Cast the dynamic reference to a statically typed reference. If the referred object is not of type T, and std::bad_any_cast will be thrown.

template<typename T>
const T &cast() const

Cast the dynamic reference to a statically typed reference. If the referred object is not of type T, and std::bad_any_cast will be thrown.

void *addr()

Get the address of the referred-to object.

const void *addr() const

Get the address of the referred-to object.

template<typename T>
any_ref py::make_any_ref(T &ob)

Convert a statically typed reference into a dynamically typed reference.

Return

The dynamically typed reference.

Parameters
  • The: reference to convert.

class py::any_cref

A constant dynamic reference to a value whose type isn’t known until runtime.

This object is like std::any, except it is non-owning. The object is like a constant reference, and thus may not be assigned to.

See

make_any_cref

Public Functions

any_cref(const void *addr, const any_vtable &vtable)

Construct an any_cref from some arbitrary address and an assignment function. The assignment function pointer doubles as the run time type tag, but will never be called (because the reference is immutable).

Parameters
  • addr: The address of the referent.

  • vtable: The vtable for the type of the referent.

any_cref(any_cref&&) = default
any_cref &operator=(any_cref&&) = default
any_cref(const any_cref&) = delete
any_cref &operator=(const any_cref&) = delete
template<typename T>
bool operator!=(const T &rhs) const
template<typename T>
bool operator==(const T &rhs) const
const any_vtable &vtable() const
template<typename T>
const T &cast() const

Cast the dynamic reference to a statically typed reference. If the referred object is not of type T, and std::bad_any_cast will be thrown.

const void *addr() const

Get the address of the referred-to object.

template<typename T>
any_cref py::make_any_cref(T &ob)

Convert a statically typed reference into a dynamically typed reference.

Return

The dynamically typed reference.

Parameters
  • The: reference to convert.

any_vtable py::dtype_to_vtable(py::borrowed_ref<PyArray_Descr> dtype)

Lookup the proper any_vtable for the given numpy dtype.

Return

The any_vtable that corresponds to the given dtype.

Parameters
  • dtype: The runtime numpy dtype.

<libpy/any_vector.h>

class py::any_vector

Public Types

using reference = any_ref
using const_reference = any_cref
using iterator = generic_iterator<std::byte*, any_ref, any_cref>
using reverse_iterator = iterator
using const_iterator = generic_iterator<const std::byte*, any_cref, any_cref>
using const_reverse_iterator = const_iterator

Public Functions

any_vector() = delete
any_vector(const any_vtable &vtable)

Create an empty vector with the given vtable.

Parameters
  • vtable: The vtable for the vector.

any_vector(const any_vtable &vtable, std::size_t count)

Initialize the vector with count default constructed elements from the given vtable.

Parameters
  • vtable: The vtable for the vector.

  • count: The number of elements to default construct.

template<typename T>
any_vector(const any_vtable &vtable, std::size_t count, const T &value)

Initialize an any vector with count copies of value.

Parameters
  • vtable: The vtable for the vector.

  • count: The number of elements to fill.

  • value: The value to copy from to fill the vector.

any_vector(const any_vector &cpfrom)
any_vector(any_vector &&mvfrom) noexcept
any_vector &operator=(const any_vector &cpfrom)
any_vector &operator=(any_vector &&mvfrom) noexcept
void swap(any_vector &other) noexcept

Swap the contents of this vector with another. This can change the vtable of the two vectors.

Parameters
  • other: The vector to swap contents with.

~any_vector()
iterator begin()
const_iterator begin() const
const_iterator cbegin() const
iterator end()
const_iterator end() const
const_iterator cend() const
std::size_t size() const

Get the number of elements in this vector.

std::size_t capacity() const

Get the number of elements this vector can store before requiring a resize.

reference operator[](std::ptrdiff_t pos)
reference at(std::ptrdiff_t pos)

Runtime bounds checked accessor for the array.

Return

An any reference to the element.

Parameters
  • pos: The index into the array to access.

Exceptions
  • std::out_of_range: when pos is out of bounds for the array.

const_reference operator[](std::ptrdiff_t pos) const
const_reference at(std::ptrdiff_t pos) const

Runtime bounds checked accessor for the array.

Return

A const any reference to the element.

Parameters
  • pos: The index into the array to access.

Exceptions
  • std::out_of_range: when pos is out of bounds for the array.

reference front()

Get an any reference to the first element of this vector.

Pre

size() > 0

const_reference front() const

Get a const any reference to the first element of this vector.

Pre

size() > 0

reference back()

Get an any reference to the last element of this vector.

Pre

size() > 0

const_reference back() const

Get a const any reference to the last element of this vector.

Pre

size() > 0

void clear()

Clear all of the elements in the vector. This destroys all of the contained objects.

Post

size() == 0

Post

Invalidates all iterators.

template<typename T>
void push_back(const T &value)

Add an element to this vector.

Post

Invalidates iterators if size() == capacity() on entry.

Note

This function has a strong exception guarantee.

Parameters
  • value: The value to copy into the vector.

template<typename T>
void push_back(T &&value)

Add an element to this vector.

Post

Invalidates iterators if size() == capacity() on entry.

Note

This function has a strong exception guarantee.

Parameters
  • value: The value to move into the vector.

void pop_back()

Remove and destroy the last element from the vector.

Pre

size() > 0.

std::byte *buffer() noexcept

Get the underlying buffer for this vector.

This pointer cannot be cast to a

T[] or a T* and used as an array. Pointer arithmetic may be done on this buffer to access individual elements as a T*.
See

py::array_view::array_view(const py::any_vector&)

Correct:

// first element
T& ref = *reinterpret_cast<T*>(vec.buffer());

// nth element
T& ref = *reinterpret_cast<T*>(vec.buffer()[sizeof(T) * n]);

Do all indexing on the std::byte* because buffer() returns a pointer to the first element of a std::byte[].

Incorrect:

T& ref = reinterpret_cast<T*>(vec.buffer())[n];

operator[] can only be used with a T* when the pointer points to a member of a T[]. buffer() returns the array of bytes that provides storage for the elements, but no T[] exists.

const std::byte *buffer() const noexcept

Get the underlying buffer for this vector.

This pointer cannot be cast to a

T[] or a T* and used as an array. Pointer arithmetic may be done on this buffer to access individual elements as a T*.
See

py::array_view::array_view(const py::any_vector&)

Correct:

// first element
const T& ref = *reinterpret_cast<const T*>(vec.buffer());

// nth element
const T& ref = *reinterpret_cast<const T*>(vec.buffer()[sizeof(T) * n]);

Do all indexing on the std::byte* because buffer() returns a pointer to the first element of a std::byte[].

Incorrect:

T& ref = reinterpret_cast<T*>(vec.buffer())[n];

operator[] can only be used with a T* when the pointer points to a member of a T[]. buffer() returns the array of bytes that provides storage for the elements, but no T[] exists.

const any_vtable &vtable() const

Get the vtable for this vector.

<libpy/autoclass.h>

template<typename T, typename base, auto initialize_base, auto clear_base>
struct py::autoclass : public py::detail::autoclass_impl<autoclass<T, base, initialize_base, clear_base>, T, detail::autoclass_object<T, base>, initialize_base, clear_base>

A factory for generating a Python class that wraps instances of a C++ type.

To create a new Python type for an object that wraps a C++ type, my_type, you can write the following:

py::owned_ref<PyTypeObject> t = py::autoclass<my_type>("modname.PythonName").type();

The resulting type will have a __name__ of “PythonName”, and a __module__ of “modname”.

By default, types created with autoclass expose no functionality to Python, not even a constructor. To add a constructor to your python object, invoke the .new_ method of the autoclass, templated with the C++ signature of the constructor. For example, to create a constructor that accepts an int and a double:

py::owned_ref<PyTypeObject> t = py::autoclass<my_type>("modname.PythonName")
                                     .new_<int, double>()
                                     .type();

Only one constructor overload may be exposed to Python because Python doesn’t support function overloading. If a constructor is not provided, instances can only be constructed from C++ using py::autoclass<my_type>::construct(Args&&...).

To expose methods of your C++ type to Python, call .def, templated on the address of the C++ method you want to expose, and pass the name of the Python method to generate. For example, to expose a C++ method called foo as a Python method named bar:

py::owned_ref<PyTypeObject> t = py::autoclass<my_type>("modname.PythonName")
                                     .new_<int, double>()
                                     .def<&my_type::foo>("bar")
                                     .type();

Subclassing Existing Python Types

Python instances are composed of two parts:

  • A static C or C++ type that defines the layout of instances in memory. A

  • runtime value of type PyTypeObject, which represents the Python type of the object.

An object’s static type must contain at least the state defined by the base PyObject struct, which includes a PyTypeObject* that points to the object’s python type. In general, there is a one-to-many relationship between static object layouts and Python types (i.e. PyTypeObject*s). Objects of a given Python type always have the same layout, but multiple objects of different Python types may have the same layout if they have the same state. For example, the standard Python exceptions all have the same layout (defined by the PyBaseExceptionObject struct), but they have different Python types so that users can catch specific exceptions types.

By default, Python objects defined with autoclass<T>.type() will have a layout that looks like:

class autoclass_object : public PyObject {
    T value;
};

The PyTypeObject returned by autoclass::type will be a (Python) subclass of Python’s object type.

In rare cases, it may be useful to use autoclass to define a type that subclasses from a Python type other than object. To support this use-case, autoclass allows you to provide a few optional arguments:

  • base: the static instance type to subclass instead of PyObject.

  • initialize_base: a function which initializes the non-PyObject fields of the base struct.

  • clear_base: a function which tears down the non-PyObject fields of the base struct.

By default, the non-PyObject fields of base will just be zeroed and no cleanup is performed. Subclassing existing Python types is an advanced autoclass feature and is not guaranteed to be safe in all configurations. Please use this feature with care.

Template Parameters
  • T: The C++ type to be wrapped.

  • base: The static base type of the Python instances created.

  • initialize_base: A function used to initialize the Python base object.

  • clear_base: A function used to clear the Python base object fields.

Public Functions

autoclass<T, base, initialize_base, clear_base> &traverse()

Add a tp_traverse field to this type. This is only allowed, but required if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the traverse function. This should either be an int(T&, visitproc, void*) or int (T::*)(visitproc, void*).

autoclass<T, base, initialize_base, clear_base> &clear()

Add a tp_clear field to this type. This is only allowed if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the clear function. This should either be an int(T&) or int (T::*)().

autoclass<T, base, initialize_base, clear_base> &doc(std::string doc)

Add a docstring to this class.

Return

*this.

Parameters
  • doc:

autoclass<T, base, initialize_base, clear_base> &new_()

Add a __new__ function to this class.

Return

*this.

Template Parameters
  • impl: A function which returns a value which can be used to construct a T.

autoclass<T, base, initialize_base, clear_base> &new_()

Add a __new__ function to this class by adapting one of the constructors of T.

Return

*this.

Template Parameters
  • ConstructorArgs: The C++ signature of the constructor to use.

autoclass<T, base, initialize_base, clear_base> &len()

Add a __len__ method from T::size()

autoclass<T, base, initialize_base, clear_base> &arithmetic()

Add all of the number methods by inferring them from T’s binary operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for arithmetic.

autoclass<T, base, initialize_base, clear_base> &matmul()

Add a function as the @ (matmul) operator.

Template Parameters
  • impl: The function to add as the @ operator. This can be a free function which takes self as the first argument, or a member function.

autoclass<T, base, initialize_base, clear_base> &comparisons()

Add all of the comparisons methods by inferring them from T’s operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for the comparisons.

autoclass<T, base, initialize_base, clear_base> &unary()

Add unary operator methods __neg__ and __pos__, and __inv__ from the C++ operator-, operator+, and operator~ respectively. interface.

autoclass<T, base, initialize_base, clear_base> &conversions()

Add conversions to int, float, and bool by delegating to static_cast<U>(T).

autoclass<T, base, initialize_base, clear_base> &mapping()

Add mapping methods (__setitem__ and __getitem__) from the C++operator[]` interface.

Template Parameters
  • KeyType: The type of the keys for this mapping.

  • ValueType: The type of the values. If not provided, or explicitly void, the __setitem__ method will not be generated.

autoclass<T, base, initialize_base, clear_base> &def(std::string name)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod. See https://docs.python.org/3/c-api/structures.html#METH_CLASS for more info. Only METH_CLASS and METH_STATIC can be passed, the others are inferred from your function.

Parameters
  • name: The name of the function as it will appear in Python.

autoclass<T, base, initialize_base, clear_base> &def(std::string name, std::string doc)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod.

Parameters
  • name: The name of the function as it will appear in Python.

  • doc: The docstring of the function as it will appear in Python.

autoclass<T, base, initialize_base, clear_base> &iter()

Add a __iter__ which produces objects of a further autoclass generated type that holds onto the iterator-sentinel pair for this type.

autoclass<T, base, initialize_base, clear_base> &hash()

Add a __hash__ which uses std::hash<T>::operator().

autoclass<T, base, initialize_base, clear_base> &callable()

Add a __call__ method which defers to T::operator().

Template Parameters
  • Args: The types of the arguments. This selects the particular overload of operator() and is used to generate the method signature for __call__.

autoclass<T, base, initialize_base, clear_base> &str()

Add a __str__ method which uses operator<<(std::ostrea&, T).

autoclass<T, base, initialize_base, clear_base> &repr()

Add a __repr__ method which uses the user provided function. The function may either be a member function of T, or a free function that takes a T&. The function must return an iterable of characters to be interpreted as utf-8.

owned_ref<PyTypeObject> type()

Get a reference to the Python type that represents a boxed T.

This function always returns a non-null pointer, but may throw an exception.

Note

If an exception is thrown, the state of the autoclass object is unspecified.

Public Static Functions

py::owned_ref<PyTypeObject> lookup_type()

Look up an already created type.

Return

The already created type, or nullptr if the type wasn’t yet created.

py::owned_ref construct(Args&&... args)

Construct a new Python object that wraps a T without boxing/unboxing the constructor arguments.

Return

A new reference to a Python wrapped version of T, or nullptr on failure.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

std::nullptr_t raise(Args&&... args)

Raise a Python exception with a wrapped version of T without boxing/unboxing the constructor arguments.

Return

nullptr.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

template<typename I>
struct py::autoclass_interface : public py::detail::autoclass_impl<autoclass_interface<I>, I, detail::autoclass_interface_object<I>>

Create a Python interface type from a C++ polymorphic type.

Template Parameters
  • I: The polymorphic type to adapt.

Given a polymorphic type in C++, want to be able to adapt concrete subclasses of the base type to Python types and have the following:

  • isinstance(PythonConcreteType, PythonBaseType)

  • py::from_object<const base_type&>.virtual_method() resolves to derived type’s implementation.

  • No undefined casts.

// some type with virtual methods
struct interface {
    ~interface();

    std::string f() const = 0;
};

// a concrete type that implements the interface
struct concrete_a : public interface{
    std::string f() const override {
        return  "concrete_a::f()";
    }
};

// a second concrete type that implements the interface
struct concrete_b : public interface{
private:
    std::string m_state;

public:
    concrete_b(std::string_view state) : m_state(state) {}

    std::string f() const override {
        return  "concrete_b::f(): "s + m_state;
    }

    int non_interface_method() const {
        return 42;
    }
};

To adapt these types to Python, first define the Python base type by using py::autoclass_interface:

py::owned_ref interface_pytype =
    py::autoclass_interface<I>("Interface").type();

An interface looks mostly like a regular py::autoclass with one key restriction: new_() may not be called and the resulting Python type is abstract.

In the example above, none of the interface methods were defined on the types; however, interface methods may be defined on the interface adapting Python type and then be inherited by all types that implement this interface. Adding methods is the same as py::automethod:

py::owned_ref interface_pytype =
    py::autoclass_interface<I>("Interface")
    .def<&interface::f>("f")
    .type();

Now, the Python interface type has an f method, which is implemented by doing a virtual lookup of f on wrapped C++ data.

To register instances of an interface, you must use py::autoclass_interface_instance. For example:

py::owned_ref concrete_a_pytype =
    py::autoclass_interface_instance<concrete_a, interface>("ConcreteA")
    .new_()
    .type();

py::owned_ref concrete_b_pytype =
    py::autoclass_interface_instance<concrete_b, interface>("ConcreteB")
    .new_<std::string_view>()
    .def<&concrete_b::non_interface_method>("non_interface_method")
    .type();

Note that neither adapters for the concrete derived types needed to add the f method; however, it will be accessible from Python. Each concrete type may have different constructors or include extra non-interface methods.

NOTE: To find the Python base class to give the Python types created by py::autoclass_interface_instance, the autoclass type cache is used. This means that the Python type object returned by py::autoclass_interface must not be destroyed before the call to py::autoclass_interface_instance. py::autoclass_interface_instance take an owning reference to the type, so you won’t need to artificially extend its lifetime.

The primary reason to use an interface type over a regular py::autoclass is to be able to get polymorphic references to instances in C++. To get a polymorphic reference to an object which is an instance of a type created by py::autoclass_interface_instance, use py::from_object<const interface&>(ob) or py::from_object<interface&>(ob). Because autofunction defaults to using py::from_objects to adapt argument, polymorphic reference parameters may be adapted.

As an example, a free function will be added to the same module that contains the Python adapted types for interface, concrete_a, and concrete_b:

std::string which_f(const interface& ob) {
    return "called: "s + f();
}

Below is some Python code that illustrates the behavior of the given types and function.

from extension_module import Interface, ConcreteA, ConcreteB, which_f

a = ConcreteA()
b = ConcreteB(b'state')

assert issubclass(ConcreteA, Interface)
assert issubclass(ConcreteB, Interface)

assert isinstance(a, ConcreteA)
assert isinstance(a, Interface)

assert isinstance(b, ConcreteB)
assert isinstance(a, Interface)

which_f(a)  # b'called: concrete_a::f()'
which_f(b)  # b'called: concrete_b::f() state'

Public Functions

autoclass_interface<I> &traverse()

Add a tp_traverse field to this type. This is only allowed, but required if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the traverse function. This should either be an int(T&, visitproc, void*) or int (T::*)(visitproc, void*).

autoclass_interface<I> &clear()

Add a tp_clear field to this type. This is only allowed if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the clear function. This should either be an int(T&) or int (T::*)().

autoclass_interface<I> &doc(std::string doc)

Add a docstring to this class.

Return

*this.

Parameters
  • doc:

autoclass_interface<I> &len()

Add a __len__ method from T::size()

autoclass_interface<I> &arithmetic()

Add all of the number methods by inferring them from T’s binary operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for arithmetic.

autoclass_interface<I> &matmul()

Add a function as the @ (matmul) operator.

Template Parameters
  • impl: The function to add as the @ operator. This can be a free function which takes self as the first argument, or a member function.

autoclass_interface<I> &comparisons()

Add all of the comparisons methods by inferring them from T’s operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for the comparisons.

autoclass_interface<I> &unary()

Add unary operator methods __neg__ and __pos__, and __inv__ from the C++ operator-, operator+, and operator~ respectively. interface.

autoclass_interface<I> &conversions()

Add conversions to int, float, and bool by delegating to static_cast<U>(T).

autoclass_interface<I> &mapping()

Add mapping methods (__setitem__ and __getitem__) from the C++operator[]` interface.

Template Parameters
  • KeyType: The type of the keys for this mapping.

  • ValueType: The type of the values. If not provided, or explicitly void, the __setitem__ method will not be generated.

autoclass_interface<I> &def(std::string name)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod. See https://docs.python.org/3/c-api/structures.html#METH_CLASS for more info. Only METH_CLASS and METH_STATIC can be passed, the others are inferred from your function.

Parameters
  • name: The name of the function as it will appear in Python.

autoclass_interface<I> &def(std::string name, std::string doc)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod.

Parameters
  • name: The name of the function as it will appear in Python.

  • doc: The docstring of the function as it will appear in Python.

autoclass_interface<I> &iter()

Add a __iter__ which produces objects of a further autoclass generated type that holds onto the iterator-sentinel pair for this type.

autoclass_interface<I> &hash()

Add a __hash__ which uses std::hash<T>::operator().

autoclass_interface<I> &callable()

Add a __call__ method which defers to T::operator().

Template Parameters
  • Args: The types of the arguments. This selects the particular overload of operator() and is used to generate the method signature for __call__.

autoclass_interface<I> &str()

Add a __str__ method which uses operator<<(std::ostrea&, T).

autoclass_interface<I> &repr()

Add a __repr__ method which uses the user provided function. The function may either be a member function of T, or a free function that takes a T&. The function must return an iterable of characters to be interpreted as utf-8.

owned_ref<PyTypeObject> type()

Get a reference to the Python type that represents a boxed T.

This function always returns a non-null pointer, but may throw an exception.

Note

If an exception is thrown, the state of the autoclass object is unspecified.

Public Static Functions

py::owned_ref<PyTypeObject> lookup_type()

Look up an already created type.

Return

The already created type, or nullptr if the type wasn’t yet created.

py::owned_ref construct(Args&&... args)

Construct a new Python object that wraps a T without boxing/unboxing the constructor arguments.

Return

A new reference to a Python wrapped version of T, or nullptr on failure.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

std::nullptr_t raise(Args&&... args)

Raise a Python exception with a wrapped version of T without boxing/unboxing the constructor arguments.

Return

nullptr.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

template<typename T, typename I>
struct py::autoclass_interface_instance : public py::detail::autoclass_impl<autoclass_interface_instance<T, I>, T, detail::autoclass_interface_instance_object<T, I>, detail::initialize_interface_type<detail::autoclass_interface_instance_object<T, I>>>

Create an instance of a py::autoclass_interface.

Note

I must have already been adapted with py::autoclass_interface and the resulting Python type object must still be alive during this call.

See

py::autoclass_interface

Parameters
  • T: The concrete C++ type which is a derived type of the interface type I.

  • I: The C++ type which defines the interface.

Public Functions

autoclass_interface_instance<T, I> &traverse()

Add a tp_traverse field to this type. This is only allowed, but required if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the traverse function. This should either be an int(T&, visitproc, void*) or int (T::*)(visitproc, void*).

autoclass_interface_instance<T, I> &clear()

Add a tp_clear field to this type. This is only allowed if extra_flags & Py_TPFLAGS_HAVE_GC.

Template Parameters
  • impl: The implementation of the clear function. This should either be an int(T&) or int (T::*)().

autoclass_interface_instance<T, I> &doc(std::string doc)

Add a docstring to this class.

Return

*this.

Parameters
  • doc:

autoclass_interface_instance<T, I> &new_()

Add a __new__ function to this class.

Return

*this.

Template Parameters
  • impl: A function which returns a value which can be used to construct a T.

autoclass_interface_instance<T, I> &new_()

Add a __new__ function to this class by adapting one of the constructors of T.

Return

*this.

Template Parameters
  • ConstructorArgs: The C++ signature of the constructor to use.

autoclass_interface_instance<T, I> &len()

Add a __len__ method from T::size()

autoclass_interface_instance<T, I> &arithmetic()

Add all of the number methods by inferring them from T’s binary operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for arithmetic.

autoclass_interface_instance<T, I> &matmul()

Add a function as the @ (matmul) operator.

Template Parameters
  • impl: The function to add as the @ operator. This can be a free function which takes self as the first argument, or a member function.

autoclass_interface_instance<T, I> &comparisons()

Add all of the comparisons methods by inferring them from T’s operators.

Template Parameters
  • BinOpRHSTypes: The types to consider as valid RHS types for the comparisons.

autoclass_interface_instance<T, I> &unary()

Add unary operator methods __neg__ and __pos__, and __inv__ from the C++ operator-, operator+, and operator~ respectively. interface.

autoclass_interface_instance<T, I> &conversions()

Add conversions to int, float, and bool by delegating to static_cast<U>(T).

autoclass_interface_instance<T, I> &mapping()

Add mapping methods (__setitem__ and __getitem__) from the C++operator[]` interface.

Template Parameters
  • KeyType: The type of the keys for this mapping.

  • ValueType: The type of the values. If not provided, or explicitly void, the __setitem__ method will not be generated.

autoclass_interface_instance<T, I> &def(std::string name)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod. See https://docs.python.org/3/c-api/structures.html#METH_CLASS for more info. Only METH_CLASS and METH_STATIC can be passed, the others are inferred from your function.

Parameters
  • name: The name of the function as it will appear in Python.

autoclass_interface_instance<T, I> &def(std::string name, std::string doc)

Add a method to this class.

Return

*this.

Template Parameters
  • impl: The implementation of the method to add. If impl is a pointer to member function, it doesn’t need to have the implicit PyObject* self argument, it will just be called on the boxed value of self.

  • flags: extra flags to indicate whether a function is a static or classmethod.

Parameters
  • name: The name of the function as it will appear in Python.

  • doc: The docstring of the function as it will appear in Python.

autoclass_interface_instance<T, I> &iter()

Add a __iter__ which produces objects of a further autoclass generated type that holds onto the iterator-sentinel pair for this type.

autoclass_interface_instance<T, I> &hash()

Add a __hash__ which uses std::hash<T>::operator().

autoclass_interface_instance<T, I> &callable()

Add a __call__ method which defers to T::operator().

Template Parameters
  • Args: The types of the arguments. This selects the particular overload of operator() and is used to generate the method signature for __call__.

autoclass_interface_instance<T, I> &str()

Add a __str__ method which uses operator<<(std::ostrea&, T).

autoclass_interface_instance<T, I> &repr()

Add a __repr__ method which uses the user provided function. The function may either be a member function of T, or a free function that takes a T&. The function must return an iterable of characters to be interpreted as utf-8.

owned_ref<PyTypeObject> type()

Get a reference to the Python type that represents a boxed T.

This function always returns a non-null pointer, but may throw an exception.

Note

If an exception is thrown, the state of the autoclass object is unspecified.

Public Static Functions

py::owned_ref<PyTypeObject> lookup_type()

Look up an already created type.

Return

The already created type, or nullptr if the type wasn’t yet created.

py::owned_ref construct(Args&&... args)

Construct a new Python object that wraps a T without boxing/unboxing the constructor arguments.

Return

A new reference to a Python wrapped version of T, or nullptr on failure.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

std::nullptr_t raise(Args&&... args)

Raise a Python exception with a wrapped version of T without boxing/unboxing the constructor arguments.

Return

nullptr.

Parameters
  • args: The arguments to forward to the C++ type’s constructor.

<libpy/autofunction.h>

template<auto impl, int flags = 0>
constexpr PyMethodDef py::autofunction(const char *const name, const char *const doc = nullptr)

Wrap a function as a PyMethodDef with automatic argument unpacking and validations. This function will not receive Python’s self argument.

Return

A PyMethodDef which defines the wrapped function.

Template Parameters
  • impl: The function to wrap.

Parameters
  • name: The name of the method to expose the Python.

  • doc: The docstring to use. If not provided, the Python __doc__ attribute will be None.

template<auto impl, int flags = 0>
constexpr PyMethodDef py::automethod(const char *const name, const char *const doc = nullptr)

Wrap a function as a PyMethodDef with automatic argument unpacking and validations. This function must take a PyObject* self as a first argument.

Return

A PyMethodDef which defines the wrapped function.

Template Parameters
  • impl: The function to wrap.

Parameters
  • name: The name of the method to expose the Python.

  • doc: The docstring to use. If not provided, the Python __doc__ attribute will be None.

template<typename Name, typename T>
class py::arg::keyword

A wrapper for specifying that a type may be passed by keyword in Python.

Template Parameters

Public Types

using name = Name

The name of the keyword argument as a py::cs::char_sequence type.

using type = T

The type of the argument.

Public Functions

T &get()

Get the argument value.

const T &get() const

Get the argument value.

using py::arg::kwd = keyword<Name, T>
template<typename T, bool none_is_missing = true>
class py::arg::optional

A wrapper for specifying that a function accepts an optional argument from Python.

Public Types

using type = T

The type of the argument.

Public Functions

std::optional<T> &get()

Get the argument value.

const std::optional<T> &get() const

Get the argument value.

using py::arg::opt = optional<T, none_is_missing>
template<typename Name, typename T, bool none_is_missing>
class py::arg::optional<keyword<Name, T>, none_is_missing>

Public Types

using name = Name

The name of the keyword argument as a py::cs::char_sequence type.

using type = T

The type of the argument.

Public Functions

std::optional<T> &get()

Get the argument value.

Note

This combines both the py::arg::optional::get and py::arg::keyword::get to just give the std::optional directly.

const std::optional<T> &get() const

Get the argument value.

Note

This combines both the py::arg::optional::get and py::arg::keyword::get to just give the std::optional directly.

using py::arg::opt_kwd = opt<kwd<Name, T>, none_is_missing>
template<typename T>
class py::dispatch::adapt_argument

Extension point to adapt Python arguments to C++ arguments for autofunction adapted function.

By default, all types are adapted with py::from_object<T> where T is the type of the argument including cv qualifiers and referenceness. This can be extended to support adapting arguments that require some extra state in the transformation, for example adapting a buffer-like object into a std::string_view.

To add a custom adapted argument type, create an explicit specialization of py::dispatch::adapt_argument. The specialization should support an adapt_argument(py::borrowed_ref<>) constructor which is passed the Python input. The constructor should throw an exception if the Python object cannot be adapted to the given C++ type. The specialization should also implement a get() method which returns the C++ value to pass to the C++ function implementation. Instances of adapt_argument will outlive the C++ implementation function call, so they may be used to manage state like a Py_buffer or a lock.

The get method should either return an rvalue reference to the adapted data or move the data out of *this so that it can be forwarded to the implementation function. If the type is small like a string view, then a value can be returned directly. get() will only be called exactly once.

Public Functions

adapt_argument(py::borrowed_ref<> ob)

Construct an adapter for a given Python object.

Parameters
  • ob: The object to adapt.

decltype(m_memb) get()

Get the C++ value.

<libpy/automodule.h>

LIBPY_AUTOMODULE(parent, name, methods)

Define a Python module.

For example, to create a module my_package.submodule.my_module with two functions f and g and one type T:

LIBPY_AUTOMODULE(my_package.submodule,
                 my_module,
                 ({py::autofunction<f>("f"),
                   py::autofunction<g>("g")}))
(py::borrowed_ref<> m) {
    py::borrowed_ref t = py::autoclass<T>("T").new_().type();
    return PyObject_SetAttrString(m.get(), "T", static_cast<PyObject*>(t));
}

Parameters
  • parent: A symbol indicating the parent module.

  • name: The leaf name of the module.

  • methods: ({...}) list of objects representing the functions to add to the module. Note this list must be surrounded by parentheses.

<libpy/borrowed_ref.h>

template<typename T = PyObject>
class py::borrowed_ref

A type that explicitly indicates that a Python object is a borrowed reference. This is implicitly convertible from a regular PyObject* or a py::owned_ref. This type should be used to accept Python object parameters like:

int f(py::borrowed_ref<> a, py::borrowed_ref<> b);

This allows calling this function with a py::owned_ref, PyObject*, or a py::borrowed_ref.

py::borrowed_ref<> should be used instead of PyObject* wherever possible to avoid ambiguity.

Note

A borrowed_ref may hold a value of nullptr.

Public Types

using element_type = T

The type of the underlying pointer.

Public Functions

constexpr borrowed_ref()

Default construct a borrowed ref to a nullptr.

constexpr borrowed_ref(std::nullptr_t)
constexpr borrowed_ref(T *ref)
constexpr borrowed_ref(const py::owned_ref<T> &ref)
constexpr borrowed_ref(const borrowed_ref&) = default
constexpr borrowed_ref &operator=(const borrowed_ref &ob) = default
constexpr T *get() const

Get the underlying pointer.

Return

The pointer managed by this borrowed_ref.

constexpr operator T*() const
template<typename U = T, typename = std::enable_if_t<!std::is_same<U, PyObject>::value>>
operator PyObject*() const
T &operator*() const
T *operator->() const
operator bool() const
bool operator==(borrowed_ref other) const

Object identity comparison.

Return

get() == other.get().

bool operator!=(borrowed_ref other) const

Object identity comparison.

Return

get() != other.get().

<libpy/buffer.h>

using py::buffer = std::unique_ptr<Py_buffer, detail::buffer_free>

A smart pointer adapter for Py_buffer that ensures the underlying buffer is released.

template<typename T>
constexpr buffer_format_code py::buffer_format = {'\0'}

The Python buffor format character for the given type.

If there is no corresponding buffer format character, this template evaluates to `’\0’`.

py::buffer py::get_buffer(py::borrowed_ref<> ob, int flags)

Get a Python Py_Buffer from the given object.

Return

buf A smart-pointer adapted Py_Buffer.

Parameters
  • ob: The object to read the buffer from. The Python buffer request flags.

Exceptions
  • An: exception is thrown if ob doesn’t expose the buffer interface.

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::buffer_type_compatible” with arguments (buffer_format_code) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- template<typename T> bool buffer_type_compatible(buffer_format_code fmt)
- template<typename T> bool buffer_type_compatible(const py::buffer &buf)

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::buffer_type_compatible” with arguments (const py::buffer&) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- template<typename T> bool buffer_type_compatible(buffer_format_code fmt)
- template<typename T> bool buffer_type_compatible(const py::buffer &buf)

<libpy/build_tuple.h>

template<typename ...Args>
py::owned_ref py::build_tuple(const Args&... args)

Build a Python tuple from a variadic amount of arguments.

All parameters are adapted using py::to_object.

Return

A new Python tuple or nullptr with a Python exception set.

See

py::to_object

Parameters
  • args: The arguments to adapt into Python objects and pack into a tuple.

<libpy/call_function.h>

template<typename ...Args>
owned_ref py::call_function(py::borrowed_ref<> function, Args&&... args)

Call a python function on C++ data.

Return

The result of the function call or nullptr if an error occurred.

Parameters
  • function: The function to call

  • args: The arguments to call it with, these will be adapted to temporary python objects.

template<typename ...Args>
owned_ref py::call_function_throws(py::borrowed_ref<> function, Args&&... args)

Call a python function on C++ data.

Return

The result of the function call. If the function throws a Python exception, a py::exception will be thrown.

Parameters
  • function: The function to call

  • args: The arguments to call it with, these will be adapted to temporary python objects.

template<typename ...Args>
owned_ref py::call_method(py::borrowed_ref<> ob, const std::string &method, Args&&... args)

Call a python method on C++ data.

Return

The result of the method call or nullptr if an error occurred.

Parameters
  • ob: The object to call the method on.

  • method: The method to call, this must be null-terminated.

  • args: The arguments to call it with, these will be adapted to temporary python objects.

template<typename ...Args>
owned_ref py::call_method_throws(py::borrowed_ref<> ob, const std::string &method, Args&&... args)

Call a python method on C++ data.

Return

The result of the method call or nullptr. If the method throws a Python exception, a py::exception will be thrown.

Parameters
  • ob: The object to call the method on.

  • method: The method to call, this must be null-terminated.

  • args: The arguments to call it with, these will be adapted to temporary python objects.

<libpy/char_sequence.h>

using py::cs::char_sequence = std::integer_sequence<char, cs...>

A compile time sequence of characters.

template<typename Char, Char... cs>
constexpr char_sequence<cs...> py::cs::literals::operator""_cs()

User defined literal for creating a py::cs::char_sequence value.

using a = py::cs::char_sequence<'a', 'b', 'c', 'd'>;
using b = decltype("abcd"_cs);

static_assert(std::is_same_v<a, b>);

template<typename Char, Char... cs>
constexpr std::array<char, sizeof...(cs)> py::cs::literals::operator""_arr()

User defined literal for creating a std::array of characters.

constexpr std::array a = {'a', 'b', 'c', 'd'};
constexpr std::array b = "abcd"_arr;

static_assert(a == b);

Note

This does not add a nul terminator to the array.

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::cs::cat” with arguments (Cs) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- constexpr char_sequence cat()
- template<typename Cs, typename Ds, typename ...Ts> constexpr auto cat(Cs cs, Ds ds, Ts... es)
- template<typename Cs, typename Ds> constexpr auto cat(Cs cs, Ds ds)
- template<typename Cs> constexpr auto cat(Cs cs)

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::cs::cat” with arguments (Cs, Ds) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- constexpr char_sequence cat()
- template<typename Cs, typename Ds, typename ...Ts> constexpr auto cat(Cs cs, Ds ds, Ts... es)
- template<typename Cs, typename Ds> constexpr auto cat(Cs cs, Ds ds)
- template<typename Cs> constexpr auto cat(Cs cs)

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::cs::cat” with arguments (Cs, Ds, Ts…) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- constexpr char_sequence cat()
- template<typename Cs, typename Ds, typename ...Ts> constexpr auto cat(Cs cs, Ds ds, Ts... es)
- template<typename Cs, typename Ds> constexpr auto cat(Cs cs, Ds ds)
- template<typename Cs> constexpr auto cat(Cs cs)
template<char... cs>
constexpr auto py::cs::to_array(char_sequence<cs...>)

Convert a character sequence into a std::array with a trailing null byte.

template<char c, typename Cs>
constexpr auto py::cs::intersperse(Cs)

Intersperse a character between all the characters of a char_sequence.

Template Parameters
  • c: The character to intersperse into the sequence

Parameters
  • cs: The sequence to intersperse the character into.

template<typename J, typename ...Cs>
constexpr auto py::cs::join(J, Cs...)

Join a sequence of compile-time strings together with another compile-time string.

This is like joiner.join(cs) in Python.

Parameters
  • joiner: The string to join with.

  • cs...: The strings to join together.

<libpy/datetime64.h>

template<typename Unit>
class py::datetime64

A datetime64 represented as nanoseconds since 1970-01-01.

The comparison operators are “nat-aware” meaning comparisons to datetime64::nat() always return false.

Public Types

using unit = Unit

The value of each tick.

Public Functions

constexpr datetime64() noexcept

Default constructor provides a nat value.

template<typename Unit2>
constexpr datetime64(const datetime64<Unit2> &cpfrom) noexcept

Unit coercion constructor.

constexpr datetime64(std::int64_t value) noexcept

Constructor from the number of unit ticks since the epoch as an integral value.

Parameters
  • value: The number of unit ticks since the epoch.

template<typename Storage, typename Unit2>
constexpr datetime64(const std::chrono::duration<Storage, Unit2> &value) noexcept

Constructor from an offset from the epoch.

Parameters
  • value: The offset from the epoch.

constexpr bool isnat() const

Check if a datetime is datetime64::nat()

Return

is this nat?

constexpr operator std::int64_t() const

Override for `static_cast<std::int64_t>(datetime64)

template<typename OtherUnit>
constexpr bool identical(const datetime64<OtherUnit> &other) const

Compares the datetimes with datetime64::nat().identical(datetime64::nat()) -> true.

Return

Are these the same datetime values?

Parameters
  • other: The datetime to compare to.

constexpr bool operator==(const datetime64 &other) const
constexpr bool operator!=(const datetime64 &other) const
constexpr bool operator<(const datetime64 &other) const
constexpr bool operator<=(const datetime64 &other) const
constexpr bool operator>(const datetime64 &other) const
constexpr bool operator>=(const datetime64 &other) const
template<typename T>
constexpr auto operator+(const T &d) const
template<typename T>
datetime64 &operator+=(const T &d)
template<typename T>
constexpr auto operator-(const T &d) const
template<typename D>
constexpr auto operator-(const datetime64<D> &d) const
template<typename T>
datetime64 &operator-=(const T &d)
template<typename D>
datetime64 &operator-=(const datetime64<D> &d)

Public Static Functions

constexpr datetime64 max() noexcept

The largest representable datetime64.

constexpr datetime64 min() noexcept

The smallest representable datetime64.

constexpr datetime64 nat() noexcept

The special ‘not-a-time’ value which has nan like behavior with datetime64 objects.

constexpr datetime64 epoch() noexcept

Retrieve the epoch in the given unit.

constexpr datetime64 nyse_epoch() noexcept

1990-01-02, the first day of the zipline NYSE calendar.

using py::chrono::ns = std::chrono::duration<std::int64_t, std::nano>
using py::chrono::us = std::chrono::duration<std::int64_t, std::micro>
using py::chrono::ms = std::chrono::duration<std::int64_t, std::milli>
using py::chrono::s = std::chrono::duration<std::int64_t>
using py::chrono::m = std::chrono::duration<std::int64_t, std::ratio<60>>
using py::chrono::h = std::chrono::duration<std::int64_t, std::ratio<60 * 60>>
using py::chrono::D = std::chrono::duration<std::int64_t, std::ratio<60 * 60 * 24>>
template<typename unit>
std::to_chars_result py::to_chars(char *first, char *last, const datetime64<unit> &dt, bool compress = false)

Write a textual representation of a datetime64 into preallocated buffer.

Datetimes will be written with the equivalent of the strftime format Y-m-d T.

Return

A std::to_chars_result. This function can only fail if the provided range is not large enough to hold the textual representation of this datetime.

Parameters
  • first: The beginning of the output buffer range.

  • last: The end of the output buffer range.

  • dt: The value to write.

  • compress: Strip the time component entirely if it is 0 (midnight)

constexpr bool py::chrono::is_leapyear(std::int64_t year)

Check if year is a leap year.

constexpr auto py::chrono::time_since_epoch(int year, int month, int day)

Compute the time since the unix epoch for a given year, month and day.

Return

The time since the epoch as a std::chrono::duration.

Parameters
  • year:

  • month: The month, 1-indexed (1 = January)

  • day: The day, 1-indexed (1 = The first of the month).

<libpy/demangle.h>

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::util::demangle_string” with arguments (const char*) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- std::string demangle_string(const char *cs)
- std::string demangle_string(const std::string &cs)

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::util::demangle_string” with arguments (const std::string&) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- std::string demangle_string(const char *cs)
- std::string demangle_string(const std::string &cs)
template<typename T>
std::string py::util::type_name()

Get the name for a given type. If the demangled name cannot be given, returns the mangled name.

Return

The type’s name.

Template Parameters
  • T: The type to get the name of.

class demangle_error : public exception

Exception raised when an invalid py::demangle_string call is performed.

Subclassed by py::util::invalid_mangled_name

<libpy/dict_range.h>

class py::dict_range

A range which iterates over the (key, value) pairs of a Python dictionary.

Public Functions

dict_range(py::borrowed_ref<> map)

Create an object which iterates a Python dictionary as key, value pairs.

Note

This does not do a type check, map must be a Python dictionary.

Parameters
  • map: The map to create a range over.

iterator begin() const
iterator end() const

Public Static Functions

dict_range checked(py::borrowed_ref<> map)

Assert that map is a Python dictionary and then construct a dict_range.

Return

A new dict range.

Parameters
  • map: The object to check and then make a view over.

<libpy/exception.h>

class py::exception : public exception

A C++ exception that can be used to communicate a Python error.

Subclassed by py::invalid_conversion

Public Functions

exception()

Default constructor assumes that an exception has already been thrown.

template<typename ...Args>
exception(py::borrowed_ref<> exc, Args&&... args)

Create a wrapping exception and raise it in Python.

Parameters
  • exc: The exception type to raise.

  • args: The arguments to forward to py::raise.

detail::raise_buffer py::raise(py::borrowed_ref<> exc)

Raise an exception with a format string that is type-safe formatted.

if (failed) {
    py::raise(PyExc_ValueError)
        << "failed to do something because: "
        << reason;
    return nullptr;
}

Return

A buffer to write the error message to like a std::ostream.

See

py::raise_format

Parameters
  • exc: The Python exception type to raise.

std::nullptr_t py::raise_from_cxx_exception(const std::exception &e)

Raise a python exception from a C++ exception. If a python exception is already raised then merge their messages.

Return

Always nullptr. This allows users to write: return raise_from_cxx_exception(e)

Parameters
  • e: The C++ exception the Python exception is being raised from.

template<typename T>
struct raise_format

Handlers for formatting C++ data types into Python exception messages.

To add a new formatter, add a new explicit template specialization for the type and implement static std::ostream& f(std::ostream& out, T value) which should append the new data to the output message.

<libpy/from_object.h>

template<typename T>
decltype(auto) py::from_object(py::borrowed_ref<> ob)

Convert a Python object into a C++ object recursively.

Return

ob as a C++ object.

See

py::dispatch::from_object

Parameters
  • ob: The object to convert

template<typename T>
constexpr bool py::has_from_object = detail::has_from_object<T>::value

Compile time boolean to detect if from_object works for a given type. This exists to make it easier to use if constexpr to test this condition instead of using more complicated SFINAE.

template<typename T>
struct from_object

Dispatch struct for defining overrides for py::from_object.

To add a new dispatch, add an explicit template specialization for the type to convert with a static member function f which accepts py::borrowed_ref<> and returns a new object of type T.

<libpy/getattr.h>

py::owned_ref py::getattr(py::borrowed_ref<> ob, const std::string &attr)

Look up an attribute on a Python object and return a new owning reference.

Return

A new reference to gettattr(ob, attr) or nullptr with a Python exception set on failure.

Parameters
  • ob: The object to look up the attribute on.

  • attr: The name of the attribute to lookup.

py::owned_ref py::getattr_throws(py::borrowed_ref<> ob, const std::string &attr)

Look up an attribute on a Python object and return a new owning reference.

Return

A new reference to gettattr(ob, attr). If the attribute doesn’t exist, a py::exception will be thrown.

Parameters
  • ob: The object to look up the attribute on.

  • attr: The name of the attribute to lookup.

Warning

doxygenfunction: Unable to resolve multiple matches for function “py::nested_getattr” with arguments (py::borrowed_ref<>, const T&, const Ts&…) in doxygen xml output for project “libpy” from directory: ../doxygen-build/xml. Potential matches:

- py::owned_ref nested_getattr(py::borrowed_ref<> ob)
- template<typename T, typename ...Ts> py::owned_ref nested_getattr(py::borrowed_ref<> ob, const T &head, const Ts&... tail)
template<typename ...Ts>
py::owned_ref py::nested_getattr_throws(const Ts&... args)

Perform nested getattr calls with intermediate error checking.

Return

A new reference to getattr(gettattr(ob, attrs[0]), attrs[1]), .... If an attribute in the chain doesn’t exist, a py::exception will be thrown.

Parameters
  • ob: The root object to look up the attribute on.

  • attrs: The name of the attributes to lookup.

<libpy/gil.h>

struct py::gil

A wrapper around the threadstate.

Public Static Functions

void release()

Release the GIL. The GIL must be held.

Note

release is a low-level utility. Please see release_block for a safer alternative.

void acquire()

Acquire the GIL. The GIL must not be held.

Note

acquire is a low-level utility. Please see hold_block for a safer alternative.

void ensure_released()

Release the GIL if it is not already released.

Note

ensure_released is a low-level utility. Please see release_block for a safer alternative.

void ensure_acquired()

Acquire the GIL if we do not already hold it.

Note

ensure_acquired is a low-level utility. Please see hold_block for a safer alternative.

bool held()

Check if the gil is currently held.

struct hold_block

RAII resource for ensuring that the gil is held in a given block.

For example:

// the gil may or may not be held here
{
    py::gil::hold_block held;
    // the gil is now definitely held
}
// the gil may or may not be held here

Public Functions

void dismiss()

Reset this gil back to the state it was in when this object was created.

struct release_block

RAII resource for ensuring that the gil is released in a given block.

For example:

// the gil may or may not be released here
{
    py::gil::release_block released;
    // the gil is now definitely released
}
// the gil may or may not be released here

Public Functions

void dismiss()

Reset this gil back to the state it was in when this object was created.

<libpy/hash.h>

template<typename T, typename ...Ts>
auto py::hash_combine(T head, Ts... tail)

Combine two or more hashes into one.

template<typename ...Ts>
auto py::hash_many(const Ts&... vs)

Hash multiple values by hash_combineing them together.

template<typename ...Ts>
auto py::hash_tuple(const std::tuple<Ts...> &t)

Hash a tuple by hash_manying all the values together.

std::size_t py::hash_buffer(const char *buf, std::size_t len)

Hash a buffer of characters using the same algorithm as std::hash<std::string_view>

Return

The hash of the string.

Parameters
  • buf: The buffer to hash.

  • len: The length of the buffer.

<libpy/itertools.h>

template<typename ...Ts>
auto py::zip(Ts&&... iterables)

Create an iterator that zips its inputs together. This is designed for pair-wise iteration over other iterables.

This requires all the iterables to be the same length, otherwise an exception is thrown.

template<typename T>
auto py::enumerate(T &&iterable)

Create an iterator that iterates as pairs of {index, value}.

template<typename F, typename T>
auto py::imap(F &&f, T &&iterable)

Create an iterator that lazily applies f to every element of iterable.

for (auto v : py::imap(f, it)) {
// ...
}

behaves the same as:

for (auto& underlying : it) {
    auto v = f(underlying);
    // ...
}

Parameters
  • f: The function to apply.

  • iterable: The iterable to apply the function to.

<libpy/meta.h>

template<typename>
struct print_t

Debugging helper to get the compiler to dump a type as an error message.

Template Parameters
  • T: The type to print.

When debugging template meta-functions it is sometimes helpful to see the resulting type of an expression. To get the compiler to emit a message, instantiate print_t with the type of interest and access any member inside the type, for example ::a.

using T = std::remove_cv_t<std::remove_reference_t<const int&>>;

print_t<T>::a;

error: invalid use of incomplete type ‘struct py::meta::print_t<int>’
 print_t<T>::a;
         ^

In the message we see: py::meta::print_t<int>, where int is the result of std::remove_cv_t<std::remove_reference_t<const int&>>.

It doesn’t matter what member is requested, ::a is chosen because it is short and easy to type, any other name will work.

template<const auto&>
struct print_v

Debugging helper to get the compiler to dump a compile-time value as an error message.

Template Parameters
  • v: The value to print.

When debugging template meta-functions it is sometimes helpful to see the resulting value of an expression. To get the compiler to emit a message, instantiate print_v with the value of interest and access any member inside the type, for example ::a.

template<auto v>
unsigned long fib = fib<v - 1> + fib<v - 2>;

template<>
unsigned long fib<1> = 1;

template<>
unsigned long fib<2> = 1;

unsigned long v = fib<24>;

print_v<T>::a;

error: invalid use of incomplete type ‘struct py::meta::print_v<46368>’
 print_v<v>::a;

In the message we see: py::meta::print_v<46368>, where 46368 is the value of fib<24>.

It doesn’t matter what member is requested, ::a is chosen because it is short and easy to type, any other name will work.

using py::meta::remove_cvref = std::remove_cv_t<std::remove_reference_t<T>>

Remove reference then cv-qualifiers.

template<typename Search, typename Elements>
constexpr bool py::meta::element_of = false

Boolean variable template for checking if type appears in the fields of a std::tuple.

Examples:

  • element_of<int, std::tuple<float, int>> evaluates to true.

  • element_of<int, std::tuple<float, float>> evaluates to false.

Template Parameters
  • Search: The type to be searched for.

  • Elements: The types of parameters appearing in the tuple.

template<typename Needle, typename Haystack>
constexpr std::size_t py::meta::search_tuple = detail::search_impl<0, Needle, Haystack>::value

Variable template for getting the index at which a type appears in the fields of a std::tuple.

Examples

  • search_tuple<int, std::tuple<float, double, int> evaluates to 2.

  • search_tuple<int, std::tuple<float, int, double> evaluates to 1.

  • search_tuple<int, std::tuple<float, double> will fail to compile.

Template Parameters
  • Needle: The type to be searched for.

  • Haystack: std::tuple of types in which to search.

using py::meta::type_cat = typename detail::type_cat_impl<Ts...>::type

Concatenate the types in a tuple into a single flattened tuple.

Template Parameters
  • Ts: The tuples to concat.

using py::meta::set_diff = typename detail::set_diff_impl<A, B>::type

Take the set difference of the types in A and B.

Examples:

  • set_diff<std::tuple<int, float, double>, std::tuple<int>> evaluates to std::tuple<float, double>.

  • set_diff<std::tuple<int, long, float, double>, std::tuple<long, int>> evaluates to std::tuple<float, double>.

    Template Parameters
    • A: The left hand side of the difference.

    • B: The right hand side of the difference.

op operator function objects

Each of these types implements operator() to defer to the named operator while attempting to preserve all the observable properties of calling the underlying operator directly.

struct add
struct sub
struct mul
struct rem
struct div
struct lshift
struct rshift
struct and_
struct xor_
struct or_
struct gt
struct ge
struct eq
struct le
struct lt
struct ne
struct neg
struct pos
struct inv

<libpy/ndarray_view.h>

template<typename T, std::size_t ndim, bool = ndim != 1>
class py::ndarray_view

A struct to wrap an array of type T whose shape is not known until runtime.

Template Parameters
  • T: The type of the elements in the array.

  • ndim: The rank of the array.

Public Types

using buffer_type = std::conditional_t<std::is_const_v<T>, const std::byte*, std::byte*>
using value_type = T
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = value_type&
using const_reference = const value_type&
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

ndarray_view(const ndarray_view<std::remove_const_t<T>, ndim> &cpfrom)
ndarray_view &operator=(const ndarray_view<std::remove_const_t<T>, ndim> &cpfrom)
ndarray_view() noexcept

Default constructor creates an empty view over nothing.

ndarray_view(T *buffer, const std::array<std::size_t, ndim> shape, const std::array<std::int64_t, ndim> &strides)

Take a view over buffer.

Parameters
  • buffer: The buffer to take a view over.

  • shape: The number of elements in the buffer along each axis.

  • stride: The number of bytes between elements along each axis.

template<typename ...Ixs>
T &at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

T &at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

template<typename ...Ixs>
T &operator()(Ixs... ixs) const
T &operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

buffer_type buffer() const

Get the underlying buffer for this view.

ndarray_view<const T, ndim> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

template<typename U>
void fill(U &&value) const

Fill the array view with value. This copies value to each index in the view.

Parameters
  • value: The value to fill the underlying array with.

bool operator==(const ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

Public Static Functions

template<typename U = T>
std::enable_if_t<py::buffer_format<U> != '\0', std::tuple<ndarray_view<T, ndim>, py::buffer>> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view virtual_array(T &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()
template<typename T>
class py::ndarray_view<T, 1, false> : public py::ndarray_view<T, 1, true>

Partial template specialization for arrays with ndim() == 1. These arrays arrays are also ranges and support operator[].

Template Parameters
  • T: The type of the elements in the array.

Public Types

using buffer_type = typename generic_ndarray_impl::buffer_type
using iterator = generic_iterator<typename generic_ndarray_impl::value_type>
using const_iterator = generic_iterator<const typename generic_ndarray_impl::value_type>
using reverse_iterator = iterator
using const_reverse_iterator = const_iterator
using value_type = T
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = value_type&
using const_reference = const value_type&
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

template<typename C, typename = std::enable_if_t<std::is_same_v<decltype(std::declval<C>().data()), std::remove_const_t<T>*>>>
ndarray_view(C &contiguous_container)

Create a view over an arbitrary contiguous container of Ts.

Parameters
  • contiguous_container: The container to take a view of.

template<typename C, typename = std::enable_if_t<std::is_const_v<T> && std::is_same_v<decltype(std::declval<C>().data()), std::remove_const_t<T>*>>>
ndarray_view(const C &contiguous_container)

Create a view over an arbitrary contiguous container of Ts.

Parameters
  • contiguous_container: The container to take a view of.

iterator begin() const
const_iterator cbegin() const
iterator end() const
const_iterator cend() const
reverse_iterator rbegin() const
const_reverse_iterator crbegin() const
reverse_iterator rend() const
const_reverse_iterator crend() const
T &operator[](std::size_t pos) const

Access the element at the given index without bounds checking.

Return

A view of the string at the given index. Undefined if pos is out of bounds.

Parameters
  • pos: The index to lookup.

T &front() const

Access the first element of this array. The array must be non-empty.

T &back() const

Access the last element of this array. The array must be non-empty.

ndarray_view slice(std::int64_t start, std::int64_t stop = snpos, std::int64_t step = 1) const

Create a view over a subsection of the viewed memory.

Return

A view over a subset of the memory.

Parameters
  • start: The start index of the slice.

  • stop: The stop index of the slice, exclusive.

  • step: The value to increment each index by.

T &at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

T &at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

T &operator()(Ixs... ixs) const
T &operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

buffer_type buffer() const

Get the underlying buffer for this view.

ndarray_view<const T, ndim> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

void fill(U &&value) const

Fill the array view with value. This copies value to each index in the view.

Parameters
  • value: The value to fill the underlying array with.

bool operator==(const ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

Public Static Functions

ndarray_view virtual_array(T &value, const std::array<std::size_t, 1> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

ndarray_view virtual_array(T &value, std::size_t size)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • size: The size of the array.

std::enable_if_t<py::buffer_format<U> != '\0', std::tuple<ndarray_view<T, ndim>, py::buffer>> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view virtual_array(T &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()

Public Static Attributes

constexpr std::size_t npos = -1
constexpr std::int64_t snpos = std::numeric_limits<std::int64_t>::max()
using py::array_view = ndarray_view<T, 1>

Helper alias for creating 1d array views.

Template Parameters
  • T: The type of the elements being viewed.

template<typename T, std::size_t ndim, typename UnaryFunction>
UnaryFunction py::for_each_unordered(py::ndarray_view<T, ndim> view, UnaryFunction f)

Apply a function to each element of an ndarray view in an unspecified order.

Parameters
  • view: The view to traverse.

  • f: The function to apply.

Type Erased Views

These views use a py::any_vtable object to view a type-erased buffer of data. Operations that would normally return references return py::any_ref or py::any_ref objects. These partial specializations implement the same protocol as the non type-erased version; however, extra methods are added to interact with the vtable or to cast the data back to some statically known type.

template<std::size_t ndim, bool higher_dimensional>
class py::ndarray_view<any_cref, ndim, higher_dimensional> : public py::detail::any_ref_ndarray_view<ndim, any_cref, higher_dimensional>

Explicit specialization for nd array const views with type-erased values.

Operations on this type of view will return py::any_cref objects instead of references to some statically known type.

Public Types

using buffer_type = std::conditional_t<std::is_same_v<any_cref, py::any_cref>, const std::byte*, std::byte*>
using value_type = any_cref
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = any_cref
using const_reference = any_cref
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

ndarray_view<any_cref, ndim, higher_dimensional> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

reference at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

reference at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

reference operator()(Ixs... ixs) const
reference operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

ndarray_view<U, ndim> cast() const

Cast the array to a static type.

auto buffer() const

Get the underlying buffer for this view.

void fill(const U &value) const
void fill(const py::any_cref &value) const
void fill(const py::any_ref &value) const
bool operator==(const any_ref_ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

bool operator!=(const any_ref_ndarray_view &other) const

Check if two views are not exactly identical.

Return

Are these views not identical?

Parameters
  • other: The view to compare to.

const any_vtable &vtable() const

Public Static Functions

std::tuple<ndarray_view<any_cref, ndim>, py::buffer> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view<any_cref, ndim> virtual_array(U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

ndarray_view<any_cref, ndim> virtual_array(const U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()

Public Static Attributes

constexpr std::size_t npos = generic_ndarray_impl::npos
template<std::size_t ndim, bool higher_dimensional>
class py::ndarray_view<any_ref, ndim, higher_dimensional> : public py::detail::any_ref_ndarray_view<ndim, any_ref, higher_dimensional>

Explicit specialization for nd array views with type-erased values.

Operations on this type of view will return py::any_ref objects instead of references to some statically known type.

Public Types

using buffer_type = std::conditional_t<std::is_same_v<any_ref, py::any_cref>, const std::byte*, std::byte*>
using value_type = any_cref
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = any_ref
using const_reference = any_cref
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

ndarray_view<any_cref, ndim, higher_dimensional> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

reference at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

reference at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

reference operator()(Ixs... ixs) const
reference operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

ndarray_view<U, ndim> cast() const

Cast the array to a static type.

auto buffer() const

Get the underlying buffer for this view.

void fill(const U &value) const
void fill(const py::any_cref &value) const
void fill(const py::any_ref &value) const
bool operator==(const any_ref_ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

bool operator!=(const any_ref_ndarray_view &other) const

Check if two views are not exactly identical.

Return

Are these views not identical?

Parameters
  • other: The view to compare to.

const any_vtable &vtable() const

Public Static Functions

std::tuple<ndarray_view<any_ref, ndim>, py::buffer> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view<any_ref, ndim> virtual_array(U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

ndarray_view<any_ref, ndim> virtual_array(const U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()
template<>
class py::ndarray_view<any_cref, 1, false> : public py::detail::any_ref_ndarray_view<1, any_cref, false>

Explicit specialization for 1d array const views with type-erased values.

Operations on this type of view will return py::any_cref objects instead of references to some statically known type.

Public Types

using buffer_type = std::conditional_t<std::is_same_v<any_cref, py::any_cref>, const std::byte*, std::byte*>
using value_type = any_cref
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = any_cref
using const_reference = any_cref
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

ndarray_view slice(std::int64_t start, std::int64_t stop = snpos, std::int64_t step = 1) const

Create a view over a subsection of the viewed memory.

Return

A view over a subset of the memory.

Parameters
  • start: The start index of the slice.

  • stop: The stop index of the slice, exclusive.

  • step: The value to increment each index by.

ndarray_view<any_cref, 1, false> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

reference at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

reference at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

reference operator()(Ixs... ixs) const
reference operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

ndarray_view<U, ndim> cast() const

Cast the array to a static type.

auto buffer() const

Get the underlying buffer for this view.

void fill(const U &value) const
void fill(const py::any_cref &value) const
void fill(const py::any_ref &value) const
bool operator==(const any_ref_ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

bool operator!=(const any_ref_ndarray_view &other) const

Check if two views are not exactly identical.

Return

Are these views not identical?

Parameters
  • other: The view to compare to.

const any_vtable &vtable() const

Public Static Functions

std::tuple<ndarray_view<any_cref, ndim>, py::buffer> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view<any_cref, ndim> virtual_array(U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

ndarray_view<any_cref, ndim> virtual_array(const U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()

Public Static Attributes

constexpr std::size_t npos = generic_ndarray_impl::npos
constexpr std::int64_t snpos = generic_ndarray_impl::snpos
template<>
class py::ndarray_view<any_ref, 1, false> : public py::detail::any_ref_ndarray_view<1, any_ref, false>

Explicit specialization for 1d array views with type-erased values.

Operations on this type of view will return py::any_ref objects instead of references to some statically known type.

Public Types

using buffer_type = std::conditional_t<std::is_same_v<any_ref, py::any_cref>, const std::byte*, std::byte*>
using value_type = any_cref
using size_type = std::size_t
using difference_type = std::ptrdiff_t
using reference = any_ref
using const_reference = any_cref
using pointer = value_type*
using const_pointer = const value_type*

Public Functions

ndarray_view slice(std::int64_t start, std::int64_t stop = snpos, std::int64_t step = 1) const

Create a view over a subsection of the viewed memory.

Return

A view over a subset of the memory.

Parameters
  • start: The start index of the slice.

  • stop: The stop index of the slice, exclusive.

  • step: The value to increment each index by.

ndarray_view<any_cref, 1, false> freeze() const

Create a new immutable view over the same memory.

Return

The frozen view.

reference at(Ixs... pos) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • pos: The index to lookup.

reference at(const std::array<std::size_t, ndim> &ixs) const

Access the element at the given index with bounds checking.

Return

A view of the string at the given index.

Parameters
  • ixs: The index to lookup.

reference operator()(Ixs... ixs) const
reference operator()(const std::array<std::size_t, ndim> &ixs) const
std::size_t size() const

The number of elements in this array.

std::ptrdiff_t ssize() const

The number of elements in this array as a signed integer.

const std::array<std::size_t, ndim> &shape() const

The shape of this array.

const std::array<std::int64_t, ndim> &strides() const

The number of bytes to go from one element to the next.

bool is_c_contig() const

Check if the array is C contiguous.

bool is_f_contig() const

Check if the array is F contiguous.

bool is_contig() const

Check if the array is contiguous in either C or F order.

ndarray_view<U, ndim> cast() const

Cast the array to a static type.

auto buffer() const

Get the underlying buffer for this view.

void fill(const U &value) const
void fill(const py::any_cref &value) const
void fill(const py::any_ref &value) const
bool operator==(const any_ref_ndarray_view &other) const

Check if two views are exactly identical.

Return

Are these views identical?

Parameters
  • other: The view to compare to.

bool operator!=(const any_ref_ndarray_view &other) const

Check if two views are not exactly identical.

Return

Are these views not identical?

Parameters
  • other: The view to compare to.

const any_vtable &vtable() const

Public Static Functions

std::tuple<ndarray_view<any_ref, ndim>, py::buffer> from_buffer_protocol(py::borrowed_ref<> ob)
ndarray_view<any_ref, ndim> virtual_array(U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

ndarray_view<any_ref, ndim> virtual_array(const U &value, const std::array<std::size_t, ndim> &shape)

Create a virtual array of length size holding the scalar value.

Return

The new mutable array view.

Parameters
  • value: The value to fill the array with.

  • shape: The shape of the array.

constexpr std::size_t rank()

Public Static Attributes

constexpr std::size_t npos = generic_ndarray_impl::npos
constexpr std::int64_t snpos = generic_ndarray_impl::snpos

Python

Miscellaneous

libpy.version_info = VersionInfo(major=0, minor=2, patch=3)

The ABI version of libpy.

Build

class libpy.build.LibpyExtension(*args, **kwargs)

A setuptools.Extension replacement for libpy based extensions.

*args

All positional arguments forwarded to setuptools.Extension.

optlevelint, optional

The optimization level to forward to the C++ compiler. Defaults to 0.

debug_symbolsbool, optional

Should debug symbols be generated? Defaults to True.

use_libpy_suggested_warningsbool, optional

Should libpy add it’s default set of warnings to the compiler flags. This set is picked to aid code clarity and attempt to common mistakes. Defaults to True.

werrorbool, optional

Treat warnings as errors. The libpy developers believe that most compiler warnings indicate serious problems and should fail the build. Defaults to True.

max_errorsint or None, optional

Limit the number of error messages that are shown. Defaults to None, showing all error messages.

ubsanbool, optional

Compile with ubsan? Implies optlevel=0.

**kwargs

All other keyword arguments forwarded to setuptools.Extension.

This class sets the language field to c++ because libpy only works with C++.

This class also passes -std=gnu++17 which is the minimum language standard required by libpy.

Any compiler flags added by libpy will appear before extra_compile_args. This gives the user the ability to override any of libpy’s options.