For more high-level information, see the Python Bindings technical notes.
Drake developers should prefer any aliases defined here over their full spellings in pybind11
.
namespace py
is a shorthand alias to pybind11
for consistency. (This symbol cannot be exposed directly in Doxygen.)
using namespace drake::pydrake
, as this may create ambiguous aliases (especially for GCC). Instead, consider using your own alias directly to the pybind11
namespace. Namespaces | |
pysolvers | |
pysystems | |
Classes | |
class | Object |
Provides a publicly visible, but minimal, re-implementation of py::object so that a public type can be used with drake::Value<T> , while still maintaining the revelant semantics with its generic implementation (#13207). More... | |
struct | overload_cast_impl |
struct | wrap_arg_default |
Default case for argument wrapping, with pure pass-through. More... | |
Typedefs | |
using | CommonScalarPack = type_pack< double, AutoDiffXd, symbolic::Expression > |
Type pack defining common scalar types. More... | |
using | NonSymbolicScalarPack = type_pack< double, AutoDiffXd > |
Type pack for non-symbolic common scalar types. More... | |
template<template< typename... > class wrap_arg_policy, typename Signature > | |
using | wrap_arg_function = typename internal::wrap_function_impl< wrap_arg_policy >::template wrap_arg< std::function< Signature > > |
Policy for explicitly wrapping functions for a given policy. More... | |
using | py_rvp = py::return_value_policy |
Shortened alias for py::return_value_policy. More... | |
Functions | |
template<typename... Ts> | |
py::tuple | GetPyParam (type_pack< Ts... >={}) |
Gets the canonical Python parameters for each C++ type. More... | |
template<typename T > | |
std::string | TemporaryClassName (const std::string &name="TemporaryName") |
Provides a temporary, unique name for a class instantiation that will be passed to AddTemplateClass . More... | |
py::object | AddTemplateClass (py::handle scope, const std::string &template_name, py::handle py_class, py::tuple param, bool skip_rename=false) |
Adds a template class instantiation. More... | |
template<typename Class , typename... Options> | |
py::class_< Class, Options... > | DefineTemplateClassWithDefault (py::handle scope, const std::string &default_name, py::tuple param, const char *doc_string="", const std::optional< std::string > &template_suffix={}, std::optional< py::dynamic_attr > dynamic_attr={}) |
Provides a convenience wrapper for defining a template class instantiation and a default instantiation (if not already defined). More... | |
template<typename Func , typename... Extra> | |
py::object | AddTemplateFunction (py::handle scope, const std::string &name, Func &&func, py::tuple param, Extra &&... extra) |
Declares a template function. More... | |
template<typename Method , typename... Extra> | |
py::object | AddTemplateMethod (py::handle scope, const std::string &name, Method &&method, py::tuple param, Extra &&... extra) |
Declares a template method. More... | |
template<typename T , typename PyClass , typename UPack = typename internal::CastUPack<T>::Pack> | |
void | DefCast (PyClass *cls, const char *doc, UPack U_pack={}) |
Binds cast<T>() explicitly. More... | |
void | DeprecateAttribute (py::object cls, py::str name, py::str message, std::optional< std::string > date={}) |
Deprecates an attribute name of a class cls . More... | |
void | WarnDeprecated (py::str message, std::optional< std::string > date={}) |
Raises a deprecation warning. More... | |
template<typename Func > | |
auto | WrapDeprecated (py::str message, Func &&func) |
Wraps any callable (function pointer, method pointer, lambda, etc.) to emit a deprecation message. More... | |
template<typename Class , typename... Args> | |
auto | py_init_deprecated (py::str message) |
Deprecated wrapping of py::init<> . More... | |
template<typename Func > | |
auto | py_init_deprecated (py::str message, Func &&func) |
Deprecated wrapping of py::init(factory) . More... | |
template<typename Class > | |
auto | DeprecatedParamInit (py::str message) |
The deprecated flavor of ParamInit<>. More... | |
template<typename Derived > | |
auto | ToEigenRef (Eigen::VectorBlock< Derived > *derived) |
Provides a mutable Ref<> for a pointer. More... | |
template<typename T > | |
py::object | ToArray (T *ptr, int size, py::tuple shape, py::return_value_policy policy=py_rvp::reference, py::handle parent=py::handle()) |
Converts a raw array to a numpy array. More... | |
template<typename T > | |
py::object | ToArray (const T *ptr, int size, py::tuple shape, py::return_value_policy policy=py_rvp::reference, py::handle parent=py::handle()) |
Converts a raw array to a numpy array (const variant). More... | |
py::object | WrapToMatchInputShape (py::handle func) |
Wraps a overload instance method to reshape the output to be the same as a given input argument. More... | |
template<typename Class , typename ModuleOrClass > | |
void | BindIdentifier (ModuleOrClass m, const std::string &name, const char *id_doc) |
Binds an Identifier instantiation. More... | |
template<typename PyClass , typename Docs > | |
void | DefAttributesUsingSerialize (PyClass *ppy_class, const Docs &cls_docs) |
Binds the attributes visited by a C++ class Serialize function as readwrite on properties its ppy_class. More... | |
template<typename PyClass > | |
void | DefAttributesUsingSerialize (PyClass *ppy_class) |
(Advanced) An overload that doesn't bind docstrings. More... | |
template<typename PyClass > | |
void | DefReprUsingSerialize (PyClass *ppy_class) |
Binds repr using a C++ class Serialize function. More... | |
template<typename Class > | |
auto | BindTypeSafeIndex (py::module m, const std::string &name, const std::string &class_doc="") |
Binds a TypeSafeIndex instantiation along with its Value[Class] type-erasure wrapper. More... | |
template<typename T , typename Class = drake::Value<T>> | |
py::class_< Class, drake::AbstractValue > | AddValueInstantiation (py::module scope) |
Defines an instantiation of pydrake.common.value.Value[...] . More... | |
template<template< typename... > class wrap_arg_policy, bool use_functions = true, typename Func = void> | |
auto | WrapFunction (Func &&func) |
Wraps the types used in a function signature to produce a new function with wrapped arguments and return value (if non-void). More... | |
template<typename Func > | |
auto | WrapCallbacks (Func &&func) |
Ensures that any std::function<> arguments are wrapped such that any T& (which can infer for T = const U ) is wrapped as U* (and conversely unwrapped when returned). More... | |
template<typename PyClass , typename Class , typename T > | |
void | DefReadWriteKeepAlive (PyClass *cls, const char *name, T Class::*member, const char *doc="") |
Idempotent to pybind11's def_readwrite() , with the exception that the setter is protected with keep_alive on a member variable that is a bare pointer. More... | |
template<typename PyClass , typename Class , typename T > | |
void | DefReadUniquePtr (PyClass *cls, const char *name, const std::unique_ptr< T > Class::*member, const char *doc="") |
Idempotent to pybind11's def_readonly() , which works for unique_ptr elements; the getter is protected with keep_alive on a member variable that is a unique_ptr. More... | |
template<typename PyClass , typename Class , typename T > | |
void | DefReadUniquePtr (PyClass *cls, const char *name, const copyable_unique_ptr< T > Class::*member, const char *doc="") |
void | DefineGeometryCommon (py::module m) |
Defines the common elements in the drake::geometry namespace. More... | |
void | DefineGeometryHydro (py::module m) |
Defines all of the hydroelastic-specific entities. More... | |
void | DefineGeometryMeshes (py::module m) |
Defines the basic mesh types (and some parsing operations) on those types. More... | |
void | DefineGeometryOptimization (py::module m) |
Defines all elements in the drake::geometry::optimization namespace. More... | |
void | DefineGeometryRender (py::module m) |
Binds the public API of the drake/geometry/render and drake/geometry/render_* directories. More... | |
void | DefineGeometrySceneGraph (py::module m) |
Binds SceneGraph and its query-related classes. More... | |
void | DefineGeometryVisualizers (py::module m) |
Binds the visualizers in drake::geometry. More... | |
geometry::optimization::ConvexSets | CloneConvexSets (const std::vector< geometry::optimization::ConvexSet * > &sets_in) |
Deep-copies the ConvexSet pointers in the given list into the C++-compatible object ConvexSets (which uses copyable_unique_ptr ownership). More... | |
template<typename PyClass > | |
void | DefCopyAndDeepCopy (PyClass *ppy_class) |
Binds Pythonic __copy__ and __deepcopy__ using class's copy constructor. More... | |
template<typename PyClass > | |
void | DefClone (PyClass *ppy_class) |
Binds Pythonic __copy__ and __deepcopy__ for a class, as well as Clone method, using class's Clone method rather than the copy constructor. More... | |
template<typename Class > | |
auto | ParamInit () |
Returns a constructor for creating an instance of Class and initializing parameters (bound using def_readwrite ). More... | |
void | ExecuteExtraPythonCode (py::module m, bool use_subdir=false) |
Executes Python code to introduce additional symbols for a given module. More... | |
void | DefineFrameworkPySemantics (py::module m) |
void | DefineFrameworkDiagramBuilder (py::module m) |
void | DefineFrameworkPySystems (py::module m) |
void | DefineFrameworkPyValues (py::module m) |
Handling special non-POD scalar types. | |
Because we use dtype=object in NumPy, we cannot alias (share references to) the data underlying matrix objects when passing data between NumPy and Eigen (see #8116). The simple policy these functions help enforce:
| |
template<typename T > | |
py::return_value_policy | return_value_policy_for_scalar_type () |
Permits referencing for builtin dtypes (e.g., T == double), but then switches to copying for custom dtypes (T ∈ {AutoDiffXd, Expression}). More... | |
template<typename SomeBlock > | |
decltype(auto) | CopyIfNotPodType (const SomeBlock &x) |
A no-op for builtin dtypes (e.g., T == double), but then switches to copying for custom dtypes (T ∈ {AutoDiffXd, Expression}). More... | |
Variables | |
template<typename Return , typename... Args> | |
constexpr auto | overload_cast_explicit = overload_cast_impl<Return, Args...>{} |
Provides option to provide explicit signature when py::overload_cast<Args...> fails to infer the Return argument. More... | |
using CommonScalarPack = type_pack< double, AutoDiffXd, symbolic::Expression> |
Type pack defining common scalar types.
using NonSymbolicScalarPack = type_pack< double, AutoDiffXd> |
Type pack for non-symbolic common scalar types.
using py_rvp = py::return_value_policy |
Shortened alias for py::return_value_policy.
For more information, see the Return Value Policy section.
using wrap_arg_function = typename internal::wrap_function_impl< wrap_arg_policy>::template wrap_arg<std::function<Signature> > |
Policy for explicitly wrapping functions for a given policy.
py::object drake::pydrake::AddTemplateClass | ( | py::handle | scope, |
const std::string & | template_name, | ||
py::handle | py_class, | ||
py::tuple | param, | ||
bool | skip_rename = false |
||
) |
Adds a template class instantiation.
scope | Parent scope of the template. |
template_name | Name of the template. |
py_class | Class instantiation to be added. |
py::class_<Class, ...>(m, TemporaryClassName<Class>().c_str())
. param | Parameters for the instantiation. |
py::object drake::pydrake::AddTemplateFunction | ( | py::handle | scope, |
const std::string & | name, | ||
Func && | func, | ||
py::tuple | param, | ||
Extra &&... | extra | ||
) |
Declares a template function.
scope | Parent scope of the template. |
name | Name of the template. |
func | Function to be added. |
param | Parameters for the instantiation. |
extra... | Additional arguments to pass to py::cpp_function . |
py::object drake::pydrake::AddTemplateMethod | ( | py::handle | scope, |
const std::string & | name, | ||
Method && | method, | ||
py::tuple | param, | ||
Extra &&... | extra | ||
) |
Declares a template method.
scope | Parent scope of the template. This should be a class. |
name | Name of the template. |
method | Method to be added. |
param | Parameters for the instantiation. |
extra... | Additional arguments to pass to py::cpp_function . |
py::class_<Class, drake::AbstractValue> drake::pydrake::AddValueInstantiation | ( | py::module | scope | ) |
Defines an instantiation of pydrake.common.value.Value[...]
.
This is only meant to bind Value<T>
(or specializations thereof). @prereq T
must have already been exposed to pybind11
.
scope | Parent scope. |
T | Inner parameter of Value<T> . |
Class | Class to be bound. By default, Value<T> is used. |
void drake::pydrake::BindIdentifier | ( | ModuleOrClass | m, |
const std::string & | name, | ||
const char * | id_doc | ||
) |
Binds an Identifier instantiation.
auto drake::pydrake::BindTypeSafeIndex | ( | py::module | m, |
const std::string & | name, | ||
const std::string & | class_doc = "" |
||
) |
Binds a TypeSafeIndex instantiation along with its Value[Class] type-erasure wrapper.
geometry::optimization::ConvexSets drake::pydrake::CloneConvexSets | ( | const std::vector< geometry::optimization::ConvexSet * > & | sets_in | ) |
Deep-copies the ConvexSet pointers in the given list into the C++-compatible object ConvexSets (which uses copyable_unique_ptr ownership).
This is useful to accept Python-natural function arguments (list of pointers) and then call the C++ API that requires a more complicated type.
decltype(auto) drake::pydrake::CopyIfNotPodType | ( | const SomeBlock & | x | ) |
A no-op for builtin dtypes (e.g., T == double), but then switches to copying for custom dtypes (T ∈ {AutoDiffXd, Expression}).
SomeBlock | an Eigen::Block or Eigen::VectorBlock. |
void drake::pydrake::DefAttributesUsingSerialize | ( | PyClass * | ppy_class, |
const Docs & | cls_docs | ||
) |
Binds the attributes visited by a C++ class Serialize function as readwrite on properties its ppy_class.
This function only works for classes with a trivial Serialize function that uses DRAKE_NVP on each of its member fields; Serialize functions that use DRAKE_NVP on temporary stack variables are not supported. The class also must be default-constructible.
void drake::pydrake::DefAttributesUsingSerialize | ( | PyClass * | ppy_class | ) |
(Advanced) An overload that doesn't bind docstrings.
We expect that pydrake bindings should always pass a Docs class (i.e., use the other overload), in some cases (especially downstream projects) that might not be possible.
void drake::pydrake::DefCast | ( | PyClass * | cls, |
const char * | doc, | ||
UPack | U_pack = {} |
||
) |
Binds cast<T>()
explicitly.
void drake::pydrake::DefClone | ( | PyClass * | ppy_class | ) |
Binds Pythonic __copy__
and __deepcopy__
for a class, as well as Clone
method, using class's Clone
method rather than the copy constructor.
void drake::pydrake::DefCopyAndDeepCopy | ( | PyClass * | ppy_class | ) |
Binds Pythonic __copy__
and __deepcopy__
using class's copy constructor.
void drake::pydrake::DefineFrameworkDiagramBuilder | ( | py::module | m | ) |
void drake::pydrake::DefineFrameworkPySemantics | ( | py::module | m | ) |
void drake::pydrake::DefineFrameworkPySystems | ( | py::module | m | ) |
void drake::pydrake::DefineFrameworkPyValues | ( | py::module | m | ) |
void drake::pydrake::DefineGeometryCommon | ( | py::module | m | ) |
Defines the common elements in the drake::geometry namespace.
See geometry_py_common.cc.
void drake::pydrake::DefineGeometryHydro | ( | py::module | m | ) |
Defines all of the hydroelastic-specific entities.
See geometry_py_hydro.cc
void drake::pydrake::DefineGeometryMeshes | ( | py::module | m | ) |
Defines the basic mesh types (and some parsing operations) on those types.
See geometry_py_meshes.cc.
void drake::pydrake::DefineGeometryOptimization | ( | py::module | m | ) |
Defines all elements in the drake::geometry::optimization namespace.
See geometry_py_optimization.cc.
void drake::pydrake::DefineGeometryRender | ( | py::module | m | ) |
Binds the public API of the drake/geometry/render and drake/geometry/render_* directories.
See geometry_py_render.cc.
void drake::pydrake::DefineGeometrySceneGraph | ( | py::module | m | ) |
Binds SceneGraph and its query-related classes.
See geometry_py_scene_graph.cc.
void drake::pydrake::DefineGeometryVisualizers | ( | py::module | m | ) |
Binds the visualizers in drake::geometry.
See geometry_py_visualizers.cc.
py::class_<Class, Options...> drake::pydrake::DefineTemplateClassWithDefault | ( | py::handle | scope, |
const std::string & | default_name, | ||
py::tuple | param, | ||
const char * | doc_string = "" , |
||
const std::optional< std::string > & | template_suffix = {} , |
||
std::optional< py::dynamic_attr > | dynamic_attr = {} |
||
) |
Provides a convenience wrapper for defining a template class instantiation and a default instantiation (if not already defined).
The default instantiation is named default_name
, while the template is named default_name + template_suffix
. The template_suffix
defaults to "_" when not provided. The caller may opt-in to py::dynamic_attr() as the last argument.
void drake::pydrake::DefReadUniquePtr | ( | PyClass * | cls, |
const char * | name, | ||
const std::unique_ptr< T > Class::* | member, | ||
const char * | doc = "" |
||
) |
Idempotent to pybind11's def_readonly()
, which works for unique_ptr elements; the getter is protected with keep_alive on a member
variable that is a unique_ptr.
PyClass | the python class. |
Class | the C++ class. |
T | type for the member we wish to apply keep alive semantics. |
void drake::pydrake::DefReadUniquePtr | ( | PyClass * | cls, |
const char * | name, | ||
const copyable_unique_ptr< T > Class::* | member, | ||
const char * | doc = "" |
||
) |
void drake::pydrake::DefReadWriteKeepAlive | ( | PyClass * | cls, |
const char * | name, | ||
T Class::* | member, | ||
const char * | doc = "" |
||
) |
Idempotent to pybind11's def_readwrite()
, with the exception that the setter is protected with keep_alive on a member
variable that is a bare pointer.
Should not be used for unique_ptr members.
PyClass | the python class. |
Class | the C++ class. |
T | type for the member we wish to apply keep alive semantics. |
void drake::pydrake::DefReprUsingSerialize | ( | PyClass * | ppy_class | ) |
Binds repr using a C++ class Serialize function.
The class must be default-constructible.
void drake::pydrake::DeprecateAttribute | ( | py::object | cls, |
py::str | name, | ||
py::str | message, | ||
std::optional< std::string > | date = {} |
||
) |
Deprecates an attribute name
of a class cls
.
This only works with class attributes (unbound members or methods) as it is implemented with a Python property descriptor.
auto drake::pydrake::DeprecatedParamInit | ( | py::str | message | ) |
The deprecated flavor of ParamInit<>.
void drake::pydrake::ExecuteExtraPythonCode | ( | py::module | m, |
bool | use_subdir = false |
||
) |
Executes Python code to introduce additional symbols for a given module.
For a module with local name {name}
and use_subdir=False, the code executed will be _{name}_extra.py
; with use_subdir=True, it will be {name}/_{name}_extra.py
. See #9599 for relevant background.
py::tuple drake::pydrake::GetPyParam | ( | type_pack< Ts... > | = {} | ) |
Gets the canonical Python parameters for each C++ type.
std::exception | on the first type it encounters that is neither aliased nor registered in pybind11 . |
Ts | The types to get C++ types for. |
py::
symbol (e.g. py::object
). On Mac, this may cause failure depending on import order (e.g. trying to use Value<py::object>
between different modules). See #8704 and #13207 for more details. auto drake::pydrake::ParamInit | ( | ) |
Returns a constructor for creating an instance of Class and initializing parameters (bound using def_readwrite
).
This provides an alternative to manually enumerating each parameter as an argument using py::init<...>
and py::arg(...)
, and is useful when the C++ class only has a default constructor. Example:
Class | The C++ class. Must have a default constructor. |
auto drake::pydrake::py_init_deprecated | ( | py::str | message | ) |
Deprecated wrapping of py::init<>
.
unique_ptr
holders. If using shared_ptr
, talk to Eric. auto drake::pydrake::py_init_deprecated | ( | py::str | message, |
Func && | func | ||
) |
Deprecated wrapping of py::init(factory)
.
py::return_value_policy drake::pydrake::return_value_policy_for_scalar_type | ( | ) |
Permits referencing for builtin dtypes (e.g., T == double), but then switches to copying for custom dtypes (T ∈ {AutoDiffXd, Expression}).
std::string drake::pydrake::TemporaryClassName | ( | const std::string & | name = "TemporaryName" | ) |
Provides a temporary, unique name for a class instantiation that will be passed to AddTemplateClass
.
py::object drake::pydrake::ToArray | ( | T * | ptr, |
int | size, | ||
py::tuple | shape, | ||
py::return_value_policy | policy = py_rvp::reference , |
||
py::handle | parent = py::handle() |
||
) |
Converts a raw array to a numpy array.
py::object drake::pydrake::ToArray | ( | const T * | ptr, |
int | size, | ||
py::tuple | shape, | ||
py::return_value_policy | policy = py_rvp::reference , |
||
py::handle | parent = py::handle() |
||
) |
Converts a raw array to a numpy array (const
variant).
auto drake::pydrake::ToEigenRef | ( | Eigen::VectorBlock< Derived > * | derived | ) |
Provides a mutable Ref<> for a pointer.
Meant to be used for decorating methods passed to pybind11
(e.g. virtual function dispatch).
void drake::pydrake::WarnDeprecated | ( | py::str | message, |
std::optional< std::string > | date = {} |
||
) |
Raises a deprecation warning.
DeprecateAttribute
so that the warning is issued immediately when accessed, not only when it is called. auto drake::pydrake::WrapCallbacks | ( | Func && | func | ) |
Ensures that any std::function<>
arguments are wrapped such that any T&
(which can infer for T = const U
) is wrapped as U*
(and conversely unwrapped when returned).
Use this when you have a callback in C++ that has a lvalue reference (const or mutable) to a C++ argument or return value. Otherwise, pybind11
may try and copy the object, will be bad if either the type is a non-copyable or if you are trying to mutate the object; in this case, the copy is mutated, but not the original you care about. For more information, see: https://github.com/pybind/pybind11/issues/1241
auto drake::pydrake::WrapDeprecated | ( | py::str | message, |
Func && | func | ||
) |
Wraps any callable (function pointer, method pointer, lambda, etc.) to emit a deprecation message.
auto drake::pydrake::WrapFunction | ( | Func && | func | ) |
Wraps the types used in a function signature to produce a new function with wrapped arguments and return value (if non-void).
The wrapping is based on wrap_arg_policy
. Any types that are of the form std::function<F>
will be recursively wrapped, such that callbacks will be of a wrapped form (arguments and return types wrapped). The original form of the callbacks will still be called in the wrapped callback.
wrap_arg_policy | User-supplied argument wrapper, that must supply the static functions wrap(Arg arg) -> Wrapped and unwrap(Wrapped wrapped) -> Arg . Arg arg is the original argument, and Wrapped wrapped is the wrapped / transformed argument type. N.B. This template template parameter uses a parameter pack to allow for SFINAE. If passing a using template alias, ensure that the alias template template parameter uses a parameter pack of the exact same form. |
use_functions | If true (default), will recursively wrap callbacks. If your policy provides handling for functions, then you should set this to false. |
func | Functor to be wrapped. Returns a function with wrapped arguments and return type. If functor is a method pointer, it will return a function of the form Return ([const] Class* self, ...) . |
std::function<>
from this if you encounter inference issues downstream of this method. py::object drake::pydrake::WrapToMatchInputShape | ( | py::handle | func | ) |
Wraps a overload instance method to reshape the output to be the same as a given input argument.
The input should be the first and only argument to trigger reshaping.
This preserves the original docstrings so that they still indicate the shapes of the input and output arrays.
Example:
constexpr auto overload_cast_explicit = overload_cast_impl<Return, Args...>{} |
Provides option to provide explicit signature when py::overload_cast<Args...>
fails to infer the Return argument.