Drake
drake::pydrake Namespace Reference

Detailed Description

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.)

Note
Downstream users should avoid 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 &name, py::handle py_class, py::tuple param)
 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::string &template_suffix="_")
 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)
 Converts a raw array to a numpy array. More...
 
template<typename T >
py::object ToArray (const T *ptr, int size, py::tuple shape)
 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 >
auto BindTypeSafeIndex (py::module m, const std::string &name, const std::string &class_doc="")
 Binds a TypeSafeIndex instantiation. More...
 
template<typename T , typename Class = drake::Value<T>>
py::class_< Class, drake::AbstractValueAddValueInstantiation (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="")
 
py::object py_keep_alive (py::object nurse, py::object patient)
 Use this when you must do manual casting - e.g. More...
 
template<typename PyType >
PyType py_keep_alive_iterable (PyType nurses, py::object patient)
 Use this to manually cast an iterable type (e.g. 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)
 Executes Python code to introduce additional symbols for a given module. More...
 
void DefineFrameworkPySemantics (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:

  • When T is double, allow referencing (do not require copying).
  • When T is not double (i.e., AutoDiffXd, Expression), copy data (do not reference the data).
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...
 

Typedef Documentation

◆ CommonScalarPack

Type pack defining common scalar types.

◆ NonSymbolicScalarPack

Type pack for non-symbolic common scalar types.

◆ py_rvp

using py_rvp = py::return_value_policy

Shortened alias for py::return_value_policy.

For more information, see the Return Value Policy section.

◆ wrap_arg_function

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.

Function Documentation

◆ AddTemplateClass()

py::object drake::pydrake::AddTemplateClass ( py::handle  scope,
const std::string &  name,
py::handle  py_class,
py::tuple  param 
)

Adds a template class instantiation.

Parameters
scopeParent scope of the template.
nameName of the template.
py_classClass instantiation to be added.
Note
The class name should be unique. If you would like automatic unique names, consider constructing the class binding as py::class_<Class, ...>(m, TemporaryClassName<Class>().c_str()).
Parameters
paramParameters for the instantiation.

◆ AddTemplateFunction()

py::object drake::pydrake::AddTemplateFunction ( py::handle  scope,
const std::string &  name,
Func &&  func,
py::tuple  param,
Extra &&...  extra 
)

Declares a template function.

Parameters
scopeParent scope of the template.
nameName of the template.
funcFunction to be added.
paramParameters for the instantiation.
extra...Additional arguments to pass to py::cpp_function.

◆ AddTemplateMethod()

py::object drake::pydrake::AddTemplateMethod ( py::handle  scope,
const std::string &  name,
Method &&  method,
py::tuple  param,
Extra &&...  extra 
)

Declares a template method.

Parameters
scopeParent scope of the template. This should be a class.
nameName of the template.
methodMethod to be added.
paramParameters for the instantiation.
extra...Additional arguments to pass to py::cpp_function.

◆ AddValueInstantiation()

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.

Parameters
scopeParent scope.
Template Parameters
TInner parameter of Value<T>.
ClassClass to be bound. By default, Value<T> is used.
Returns
Reference to the registered Python type.

◆ BindTypeSafeIndex()

auto drake::pydrake::BindTypeSafeIndex ( py::module  m,
const std::string &  name,
const std::string &  class_doc = "" 
)

Binds a TypeSafeIndex instantiation.

◆ CopyIfNotPodType()

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}).

Template Parameters
SomeBlockan Eigen::Block or Eigen::VectorBlock.

◆ DefCast()

void drake::pydrake::DefCast ( PyClass *  cls,
const char *  doc,
UPack  U_pack = {} 
)

Binds cast<T>() explicitly.

◆ DefClone()

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.

◆ DefCopyAndDeepCopy()

void drake::pydrake::DefCopyAndDeepCopy ( PyClass *  ppy_class)

Binds Pythonic __copy__ and __deepcopy__ using class's copy constructor.

Note
Do not use this if the class's copy constructor does not imply a deep copy.

◆ DefineFrameworkPySemantics()

void drake::pydrake::DefineFrameworkPySemantics ( py::module  m)

◆ DefineFrameworkPySystems()

void drake::pydrake::DefineFrameworkPySystems ( py::module  m)

◆ DefineFrameworkPyValues()

void drake::pydrake::DefineFrameworkPyValues ( py::module  m)

◆ DefineTemplateClassWithDefault()

py::class_<Class, Options...> drake::pydrake::DefineTemplateClassWithDefault ( py::handle  scope,
const std::string &  default_name,
py::tuple  param,
const char *  doc_string = "",
const std::string &  template_suffix = "_" 
)

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.

Returns
pybind11 class

◆ DefReadUniquePtr() [1/2]

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.

Template Parameters
PyClassthe python class.
Classthe C++ class.
Ttype for the member we wish to apply keep alive semantics.

◆ DefReadUniquePtr() [2/2]

void drake::pydrake::DefReadUniquePtr ( PyClass *  cls,
const char *  name,
const copyable_unique_ptr< T > Class::*  member,
const char *  doc = "" 
)

◆ DefReadWriteKeepAlive()

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.

Template Parameters
PyClassthe python class.
Classthe C++ class.
Ttype for the member we wish to apply keep alive semantics.

◆ DeprecateAttribute()

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.

◆ DeprecatedParamInit()

auto drake::pydrake::DeprecatedParamInit ( py::str  message)

The deprecated flavor of ParamInit<>.

◆ ExecuteExtraPythonCode()

void drake::pydrake::ExecuteExtraPythonCode ( py::module  m)

Executes Python code to introduce additional symbols for a given module.

For a module with local name {name}, the code executed will be _{name}_extra.py. See #9599 for relevant background.

◆ GetPyParam()

py::tuple drake::pydrake::GetPyParam ( type_pack< Ts... >  = {})

Gets the canonical Python parameters for each C++ type.

Returns
Python tuple of canonical parameters.
Exceptions
std::runtime_erroron the first type it encounters that is neither aliased nor registered in pybind11.
Template Parameters
TsThe types to get C++ types for.
Precondition
Ts must be public symbols.
Ts cannot be a 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.

◆ ParamInit()

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:

using Class = ExampleClass;
py::class_<Class>(m, "ExampleClass") // BR
.def(ParamInit<Class>());
Template Parameters
ClassThe C++ class. Must have a default constructor.

◆ py_init_deprecated() [1/2]

auto drake::pydrake::py_init_deprecated ( py::str  message)

Deprecated wrapping of py::init<>.

Note
Only for unique_ptr holders. If using shared_ptr, talk to Eric.

◆ py_init_deprecated() [2/2]

auto drake::pydrake::py_init_deprecated ( py::str  message,
Func &&  func 
)

Deprecated wrapping of py::init(factory).

◆ py_keep_alive()

py::object drake::pydrake::py_keep_alive ( py::object  nurse,
py::object  patient 
)

Use this when you must do manual casting - e.g.

lists or tuples of nurses, where the container may get discarded but the items kept. Prefer this over py::cast(obj, reference_internal, parent) (pending full resolution of #11046).

◆ py_keep_alive_iterable()

PyType drake::pydrake::py_keep_alive_iterable ( PyType  nurses,
py::object  patient 
)

Use this to manually cast an iterable type (e.g.

py::list, py::set). See pydrake_pybind_test for an example. N.B. This should not be used for py::dict.

◆ return_value_policy_for_scalar_type()

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}).

◆ TemporaryClassName()

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.

◆ ToArray() [1/2]

py::object drake::pydrake::ToArray ( T *  ptr,
int  size,
py::tuple  shape 
)

Converts a raw array to a numpy array.

◆ ToArray() [2/2]

py::object drake::pydrake::ToArray ( const T *  ptr,
int  size,
py::tuple  shape 
)

Converts a raw array to a numpy array (const variant).

◆ ToEigenRef()

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).

◆ WarnDeprecated()

void drake::pydrake::WarnDeprecated ( py::str  message,
std::optional< std::string >  date = {} 
)

Raises a deprecation warning.

Note
If you are deprecating a class's member or method, please use DeprecateAttribute so that the warning is issued immediately when accessed, not only when it is called.

◆ WrapCallbacks()

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

◆ WrapDeprecated()

auto drake::pydrake::WrapDeprecated ( py::str  message,
Func &&  func 
)

Wraps any callable (function pointer, method pointer, lambda, etc.) to emit a deprecation message.

◆ WrapFunction()

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.

Template Parameters
wrap_arg_policyUser-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_functionsIf true (default), will recursively wrap callbacks. If your policy provides handling for functions, then you should set this to false.
Parameters
funcFunctor 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, ...).
Returns
Wrapped function lambda. N.B. Construct a std::function<> from this if you encounter inference issues downstream of this method.

◆ WrapToMatchInputShape()

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:

cls // BR
.def("multiply", [](const Class& self, const Class& other) { ... })
.def("multiply", [](const Class& self, const Vector3<T>& p) { ... })
.def("multiply", [](const Class& self, const Matrix3X<T>& plist) { ... });
cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply"));
See also
PydrakeReturnVectorsOrMatrices

Variable Documentation

◆ overload_cast_explicit

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.