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
ordefault_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_vtablemake
()¶
-
constexpr
-
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
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.
-
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
, andstd::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
, andstd::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_refpy
::
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.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.
-
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
, andstd::bad_any_cast
will be thrown.
-
const void *
addr
() const¶ Get the address of the referred-to object.
-
-
template<typename
T
>
any_crefpy
::
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
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 ofvalue
.- 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
()¶
-
const_iterator
begin
() const¶
-
const_iterator
cbegin
() const¶
-
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
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
: whenpos
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
: whenpos
is out of bounds for the array.
-
const_reference
front
() const¶ Get a const any reference to the first 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
>
voidpush_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
>
voidpush_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.
-
std::byte *
buffer
() noexcept¶ Get the underlying buffer for this vector.
This pointer cannot be cast to a
T[]
or aT*
and used as an array. Pointer arithmetic may be done on this buffer to access individual elements as aT*
.- 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*
becausebuffer()
returns a pointer to the first element of astd::byte[]
.Incorrect:
T& ref = reinterpret_cast<T*>(vec.buffer())[n];
operator[]
can only be used with aT*
when the pointer points to a member of aT[]
.buffer()
returns the array of bytes that provides storage for the elements, but noT[]
exists.
-
const std::byte *
buffer
() const noexcept¶ Get the underlying buffer for this vector.
This pointer cannot be cast to a
T[]
or aT*
and used as an array. Pointer arithmetic may be done on this buffer to access individual elements as aT*
.- 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*
becausebuffer()
returns a pointer to the first element of astd::byte[]
.Incorrect:
T& ref = reinterpret_cast<T*>(vec.buffer())[n];
operator[]
can only be used with aT*
when the pointer points to a member of aT[]
.buffer()
returns the array of bytes that provides storage for the elements, but noT[]
exists.
-
const any_vtable &
vtable
() const¶ Get the vtable for this vector.
-
using
<libpy/autoclass.h>
¶
-
template<typename
T
, typenamebase
, autoinitialize_base
, autoclear_base
>
structpy
::
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 theautoclass
, 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 calledfoo
as a Python method namedbar
: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 aPyTypeObject*
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 thePyBaseExceptionObject
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 byautoclass::type
will be a (Python) subclass of Python’sobject
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 ofPyObject
.initialize_base
: a function which initializes the non-PyObject
fields of thebase
struct.clear_base
: a function which tears down the non-PyObject
fields of thebase
struct.
By default, the non-
PyObject
fields ofbase
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 ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the traverse function. This should either be anint(T&, visitproc, void*)
orint (T::*)(visitproc, void*)
.
-
autoclass<T, base, initialize_base, clear_base> &
clear
()¶ Add a
tp_clear
field to this type. This is only allowed ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the clear function. This should either be anint(T&)
orint (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 aT
.
-
autoclass<T, base, initialize_base, clear_base> &
new_
() Add a
__new__
function to this class by adapting one of the constructors ofT
.- 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 fromT::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 takesself
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+
, andoperator~
respectively. interface.
-
autoclass<T, base, initialize_base, clear_base> &
conversions
()¶ Add conversions to
int
,float
, andbool
by delegating tostatic_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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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 furtherautoclass
generated type that holds onto the iterator-sentinel pair for this type.
-
autoclass<T, base, initialize_base, clear_base> &
hash
()¶ Add a
__hash__
which usesstd::hash<T>::operator()
.
-
autoclass<T, base, initialize_base, clear_base> &
callable
()¶ Add a
__call__
method which defers toT::operator()
.- Template Parameters
Args
: The types of the arguments. This selects the particular overload ofoperator()
and is used to generate the method signature for__call__
.
-
autoclass<T, base, initialize_base, clear_base> &
str
()¶ Add a
__str__
method which usesoperator<<(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 ofT
, or a free function that takes aT&
. 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
>
structpy
::
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 off
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 bypy::autoclass_interface
must not be destroyed before the call topy::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 bypy::autoclass_interface_instance
, usepy::from_object<const interface&>(ob)
orpy::from_object<interface&>(ob)
. Becauseautofunction
defaults to usingpy::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
, andconcrete_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 ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the traverse function. This should either be anint(T&, visitproc, void*)
orint (T::*)(visitproc, void*)
.
-
autoclass_interface<I> &
clear
()¶ Add a
tp_clear
field to this type. This is only allowed ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the clear function. This should either be anint(T&)
orint (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 fromT::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 takesself
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+
, andoperator~
respectively. interface.
-
autoclass_interface<I> &
conversions
()¶ Add conversions to
int
,float
, andbool
by delegating tostatic_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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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 furtherautoclass
generated type that holds onto the iterator-sentinel pair for this type.
-
autoclass_interface<I> &
hash
()¶ Add a
__hash__
which usesstd::hash<T>::operator()
.
-
autoclass_interface<I> &
callable
()¶ Add a
__call__
method which defers toT::operator()
.- Template Parameters
Args
: The types of the arguments. This selects the particular overload ofoperator()
and is used to generate the method signature for__call__
.
-
autoclass_interface<I> &
str
()¶ Add a
__str__
method which usesoperator<<(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 ofT
, or a free function that takes aT&
. 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
, typenameI
>
structpy
::
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 withpy::autoclass_interface
and the resulting Python type object must still be alive during this call.- See
- Parameters
T
: The concrete C++ type which is a derived type of the interface typeI
.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 ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the traverse function. This should either be anint(T&, visitproc, void*)
orint (T::*)(visitproc, void*)
.
-
autoclass_interface_instance<T, I> &
clear
()¶ Add a
tp_clear
field to this type. This is only allowed ifextra_flags & Py_TPFLAGS_HAVE_GC
.- Template Parameters
impl
: The implementation of the clear function. This should either be anint(T&)
orint (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 aT
.
-
autoclass_interface_instance<T, I> &
new_
() Add a
__new__
function to this class by adapting one of the constructors ofT
.- Return
*this.
- Template Parameters
ConstructorArgs
: The C++ signature of the constructor to use.
-
autoclass_interface_instance<T, I> &
len
()¶ Add a
__len__
method fromT::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 takesself
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+
, andoperator~
respectively. interface.
-
autoclass_interface_instance<T, I> &
conversions
()¶ Add conversions to
int
,float
, andbool
by delegating tostatic_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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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. Ifimpl
is a pointer to member function, it doesn’t need to have the implicitPyObject* self
argument, it will just be called on the boxed value ofself
.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 furtherautoclass
generated type that holds onto the iterator-sentinel pair for this type.
-
autoclass_interface_instance<T, I> &
hash
()¶ Add a
__hash__
which usesstd::hash<T>::operator()
.
-
autoclass_interface_instance<T, I> &
callable
()¶ Add a
__call__
method which defers toT::operator()
.- Template Parameters
Args
: The types of the arguments. This selects the particular overload ofoperator()
and is used to generate the method signature for__call__
.
-
autoclass_interface_instance<T, I> &
str
()¶ Add a
__str__
method which usesoperator<<(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 ofT
, or a free function that takes aT&
. 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
, intflags
= 0>
constexpr PyMethodDefpy
::
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
, intflags
= 0>
constexpr PyMethodDefpy
::
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
, typenameT
>
classpy::arg
::
keyword
¶ A wrapper for specifying that a type may be passed by keyword in Python.
- Template Parameters
Name
: Apy::cs::char_sequence
encoding the name.T
: The name of the argument in Python.
Public Types
-
using
name
= Name¶ The name of the keyword argument as a
py::cs::char_sequence
type.
-
template<typename
T
, boolnone_is_missing
= true>
classpy::arg
::
optional
¶ A wrapper for specifying that a function accepts an optional argument from Python.
-
template<typename
Name
, typenameT
, boolnone_is_missing
>
classpy::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.
Public Functions
-
std::optional<T> &
get
()¶ Get the argument value.
- Note
This combines both the
py::arg::optional::get
andpy::arg::keyword::get
to just give thestd::optional
directly.
-
const std::optional<T> &
get
() const¶ Get the argument value.
- Note
This combines both the
py::arg::optional::get
andpy::arg::keyword::get
to just give thestd::optional
directly.
-
using
-
template<typename
T
>
classpy::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 astd::string_view
.To add a custom adapted argument type, create an explicit specialization of
py::dispatch::adapt_argument
. The specialization should support anadapt_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 aget()
method which returns the C++ value to pass to the C++ function implementation. Instances ofadapt_argument
will outlive the C++ implementation function call, so they may be used to manage state like aPy_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 functionsf
andg
and one typeT
: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>
classpy
::
borrowed_ref
¶A type that explicitly indicates that a Python object is a borrowed reference. This is implicitly convertible from a regular
PyObject*
or apy::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 apy::borrowed_ref
.
py::borrowed_ref<>
should be used instead ofPyObject*
wherever possible to avoid ambiguity.
- Note
A
borrowed_ref
may hold a value ofnullptr
.Public Functions
- constexpr
borrowed_ref
()¶Default construct a borrowed ref to a
nullptr
.
- constexpr
borrowed_ref
(std::nullptr_t)¶
- 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¶
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_codepy
::
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 ifob
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_refpy
::
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_refpy
::
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 callargs
: The arguments to call it with, these will be adapted to temporary python objects.
-
template<typename ...
Args
>
owned_refpy
::
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 callargs
: The arguments to call it with, these will be adapted to temporary python objects.
-
template<typename ...
Args
>
owned_refpy
::
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_refpy
::
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 autopy::cs
::
to_array
(char_sequence<cs...>)¶ Convert a character sequence into a
std::array
with a trailing null byte.
<libpy/datetime64.h>
¶
-
template<typename
Unit
>
classpy
::
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 Functions
-
constexpr
datetime64
() noexcept¶ Default constructor provides a nat value.
-
template<typename
Unit2
>
constexprdatetime64
(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 ofunit
ticks since the epoch.
-
template<typename
Storage
, typenameUnit2
>
constexprdatetime64
(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 boolidentical
(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
>
datetime64 &operator+=
(const T &d)¶
-
template<typename
D
>
constexpr autooperator-
(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.
-
constexpr
-
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_resultpy
::
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
formatY-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::stringpy::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.
<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 adict_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 topy::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
>
structraise_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
- Parameters
ob
: The object to convert
-
template<typename
T
>
constexpr boolpy
::
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 useif constexpr
to test this condition instead of using more complicated SFINAE.
-
template<typename
T
>
structfrom_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 acceptspy::borrowed_ref<>
and returns a new object of typeT
.
<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)
ornullptr
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, apy::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_refpy
::
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, apy::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 seerelease_block
for a safer alternative.
-
void
acquire
()¶ Acquire the GIL. The GIL must not be held.
- Note
acquire
is a low-level utility. Please seehold_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 seerelease_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 seehold_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.
-
void
-
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.
-
void
-
void
<libpy/hash.h>
¶
-
template<typename
T
, typename ...Ts
>
autopy
::
hash_combine
(T head, Ts... tail)¶ Combine two or more hashes into one.
-
template<typename ...
Ts
>
autopy
::
hash_many
(const Ts&... vs)¶ Hash multiple values by
hash_combine
ing them together.
-
template<typename ...
Ts
>
autopy
::
hash_tuple
(const std::tuple<Ts...> &t)¶ Hash a tuple by
hash_many
ing 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
>
autopy
::
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
>
autopy
::
enumerate
(T &&iterable)¶ Create an iterator that iterates as pairs of {index, value}.
-
template<typename
F
, typenameT
>
autopy
::
imap
(F &&f, T &&iterable)¶ Create an iterator that lazily applies
f
to every element ofiterable
.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>
structprint_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>
, whereint
is the result ofstd::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&>
structprint_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>
, where46368
is the value offib<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
, typenameElements
>
constexpr boolpy::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
, typenameHaystack
>
constexpr std::size_tpy::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 tostd::tuple<float, double>
.set_diff<std::tuple<int, long, float, double>, std::tuple<long, int>>
evaluates tostd::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_tndim
, bool = ndim != 1>
classpy
::
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
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.
-
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::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
>
voidfill
(U &&value) const¶ Fill the array view with
value
. This copiesvalue
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 scalarvalue
.- 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
>
classpy
::
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 supportoperator[]
.- 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
const_reverse_iterator
= const_iterator¶
-
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
T
s.- 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
T
s.- Parameters
contiguous_container
: The container to take a view of.
-
const_iterator
cbegin
() 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.
-
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.
-
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 copiesvalue
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 scalarvalue
.- 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 scalarvalue
.- 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 scalarvalue
.- 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
()¶
-
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_tndim
, typenameUnaryFunction
>
UnaryFunctionpy
::
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
, boolhigher_dimensional
>
classpy
::
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
size_type
= std::size_t¶
-
using
difference_type
= std::ptrdiff_t¶
-
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.
-
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::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.
-
auto
buffer
() const¶ Get the underlying buffer for this view.
-
void
fill
(const U &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 scalarvalue
.- 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 scalarvalue
.- 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¶
-
using
-
template<std::size_t
ndim
, boolhigher_dimensional
>
classpy
::
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
size_type
= std::size_t¶
-
using
difference_type
= std::ptrdiff_t¶
-
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.
-
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::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.
-
auto
buffer
() const¶ Get the underlying buffer for this view.
-
void
fill
(const U &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 scalarvalue
.- 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 scalarvalue
.- 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
()¶
-
using
-
template<>
classpy
::
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
size_type
= std::size_t¶
-
using
difference_type
= std::ptrdiff_t¶
-
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.
-
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¶
-
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 scalarvalue
.- 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 scalarvalue
.- 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
()¶
-
using
-
template<>
classpy
::
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
size_type
= std::size_t¶
-
using
difference_type
= std::ptrdiff_t¶
-
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.
-
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¶
-
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 scalarvalue
.- 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 scalarvalue
.- 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
()¶
-
using
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.