2015-07-05 18:05:44 +00:00
/*
2016-01-17 21:36:44 +00:00
pybind11 / pybind11 . h : Main header file of the C + + 11 python
binding generator library
2015-07-05 18:05:44 +00:00
2016-04-17 18:21:41 +00:00
Copyright ( c ) 2016 Wenzel Jakob < wenzel . jakob @ epfl . ch >
2015-07-05 18:05:44 +00:00
All rights reserved . Use of this source code is governed by a
BSD - style license that can be found in the LICENSE file .
*/
2015-07-11 15:41:48 +00:00
# pragma once
2015-07-05 18:05:44 +00:00
2016-01-17 21:36:44 +00:00
# include "attr.h"
2021-02-23 03:15:40 +00:00
# include "gil.h"
2016-11-15 11:38:05 +00:00
# include "options.h"
2017-08-13 22:35:53 +00:00
# include "detail/class.h"
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
# include "detail/init.h"
2015-07-05 18:05:44 +00:00
2021-10-04 00:15:37 +00:00
# include <cstdlib>
2020-09-19 18:25:46 +00:00
# include <memory>
2021-07-15 16:38:52 +00:00
# include <new>
2020-09-19 18:25:46 +00:00
# include <vector>
# include <string>
# include <utility>
2022-01-11 22:57:59 +00:00
# include <cstring>
2021-07-26 18:28:36 +00:00
2021-07-15 16:38:52 +00:00
# if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
# define PYBIND11_STD_LAUNDER std::launder
# define PYBIND11_HAS_STD_LAUNDER 1
# else
# define PYBIND11_STD_LAUNDER
# define PYBIND11_HAS_STD_LAUNDER 0
# endif
2019-06-19 08:48:36 +00:00
# if defined(__GNUG__) && !defined(__clang__)
# include <cxxabi.h>
# endif
2021-07-30 14:09:55 +00:00
/* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
This warning is about ABI compatibility , not code health .
It is only actually needed in a couple places , but apparently GCC 7 " generates this warning if
and only if the first template instantiation . . . involves noexcept " [stackoverflow], therefore
it could get triggered from seemingly random places , depending on user code .
No other GCC version generates this warning .
*/
# if defined(__GNUC__) && __GNUC__ == 7
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wnoexcept-type"
# endif
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( PYBIND11_NAMESPACE )
2015-07-05 18:05:44 +00:00
2021-07-21 12:22:18 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
// Apply all the extensions translators from a list
// Return true if one of the translators completed without raising an exception
// itself. Return of false indicates that if there are other translators
// available, they should be tried.
inline bool apply_exception_translators ( std : : forward_list < ExceptionTranslator > & translators ) {
auto last_exception = std : : current_exception ( ) ;
for ( auto & translator : translators ) {
try {
translator ( last_exception ) ;
return true ;
} catch ( . . . ) {
last_exception = std : : current_exception ( ) ;
}
}
return false ;
}
2021-07-26 18:28:36 +00:00
# if defined(_MSC_VER)
# define PYBIND11_COMPAT_STRDUP _strdup
# else
# define PYBIND11_COMPAT_STRDUP strdup
# endif
2021-07-21 12:22:18 +00:00
2021-07-26 18:28:36 +00:00
PYBIND11_NAMESPACE_END ( detail )
2021-07-21 12:22:18 +00:00
2015-07-26 14:33:49 +00:00
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
2015-07-11 15:41:48 +00:00
class cpp_function : public function {
2015-07-26 14:33:49 +00:00
public :
2020-09-11 03:15:22 +00:00
cpp_function ( ) = default ;
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2017-11-07 16:35:27 +00:00
cpp_function ( std : : nullptr_t ) { }
2015-07-26 14:33:49 +00:00
2016-05-10 14:05:03 +00:00
/// Construct a cpp_function from a vanilla function pointer
2017-02-17 11:56:41 +00:00
template < typename Return , typename . . . Args , typename . . . Extra >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2017-02-17 11:56:41 +00:00
cpp_function ( Return ( * f ) ( Args . . . ) , const Extra & . . . extra ) {
2016-05-10 14:05:03 +00:00
initialize ( f , f , extra . . . ) ;
2015-07-26 14:33:49 +00:00
}
2016-05-10 14:05:03 +00:00
/// Construct a cpp_function from a lambda function (possibly with internal state)
2017-05-10 05:51:08 +00:00
template < typename Func , typename . . . Extra ,
typename = detail : : enable_if_t < detail : : is_lambda < Func > : : value > >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2017-02-17 11:56:41 +00:00
cpp_function ( Func & & f , const Extra & . . . extra ) {
2015-07-29 15:43:52 +00:00
initialize ( std : : forward < Func > ( f ) ,
2017-05-10 05:51:08 +00:00
( detail : : function_signature_t < Func > * ) nullptr , extra . . . ) ;
2015-07-26 14:33:49 +00:00
}
2020-06-10 11:35:10 +00:00
/// Construct a cpp_function from a class method (non-const, no ref-qualifier)
2017-02-17 11:56:41 +00:00
template < typename Return , typename Class , typename . . . Arg , typename . . . Extra >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2017-02-17 11:56:41 +00:00
cpp_function ( Return ( Class : : * f ) ( Arg . . . ) , const Extra & . . . extra ) {
2020-07-07 13:56:07 +00:00
initialize ( [ f ] ( Class * c , Arg . . . args ) - > Return { return ( c - > * f ) ( std : : forward < Arg > ( args ) . . . ) ; } ,
2017-02-17 11:56:41 +00:00
( Return ( * ) ( Class * , Arg . . . ) ) nullptr , extra . . . ) ;
2015-07-05 18:05:44 +00:00
}
2015-07-26 14:33:49 +00:00
2020-06-10 11:35:10 +00:00
/// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
/// A copy of the overload for non-const functions without explicit ref-qualifier
/// but with an added `&`.
template < typename Return , typename Class , typename . . . Arg , typename . . . Extra >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2020-06-10 11:35:10 +00:00
cpp_function ( Return ( Class : : * f ) ( Arg . . . ) & , const Extra & . . . extra ) {
2021-11-07 23:35:25 +00:00
initialize ( [ f ] ( Class * c , Arg . . . args ) - > Return { return ( c - > * f ) ( std : : forward < Arg > ( args ) . . . ) ; } ,
2020-06-10 11:35:10 +00:00
( Return ( * ) ( Class * , Arg . . . ) ) nullptr , extra . . . ) ;
}
/// Construct a cpp_function from a class method (const, no ref-qualifier)
2017-02-17 11:56:41 +00:00
template < typename Return , typename Class , typename . . . Arg , typename . . . Extra >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2017-02-17 11:56:41 +00:00
cpp_function ( Return ( Class : : * f ) ( Arg . . . ) const , const Extra & . . . extra ) {
2020-07-07 13:56:07 +00:00
initialize ( [ f ] ( const Class * c , Arg . . . args ) - > Return { return ( c - > * f ) ( std : : forward < Arg > ( args ) . . . ) ; } ,
2017-02-17 11:56:41 +00:00
( Return ( * ) ( const Class * , Arg . . . ) ) nullptr , extra . . . ) ;
2015-07-26 14:33:49 +00:00
}
2020-06-10 11:35:10 +00:00
/// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
/// A copy of the overload for const functions without explicit ref-qualifier
/// but with an added `&`.
template < typename Return , typename Class , typename . . . Arg , typename . . . Extra >
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
// NOLINTNEXTLINE(google-explicit-constructor)
2020-06-10 11:35:10 +00:00
cpp_function ( Return ( Class : : * f ) ( Arg . . . ) const & , const Extra & . . . extra ) {
2021-11-07 23:35:25 +00:00
initialize ( [ f ] ( const Class * c , Arg . . . args ) - > Return { return ( c - > * f ) ( std : : forward < Arg > ( args ) . . . ) ; } ,
2020-06-10 11:35:10 +00:00
( Return ( * ) ( const Class * , Arg . . . ) ) nullptr , extra . . . ) ;
}
2015-09-04 21:42:12 +00:00
/// Return the function name
2016-01-17 21:36:44 +00:00
object name ( ) const { return attr ( " __name__ " ) ; }
2015-09-04 21:42:12 +00:00
2016-01-17 21:36:41 +00:00
protected :
2021-01-14 18:34:32 +00:00
struct InitializingFunctionRecordDeleter {
// `destruct(function_record, false)`: `initialize_generic` copies strings and
// takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
void operator ( ) ( detail : : function_record * rec ) { destruct ( rec , false ) ; }
} ;
using unique_function_record = std : : unique_ptr < detail : : function_record , InitializingFunctionRecordDeleter > ;
2016-09-10 06:28:37 +00:00
/// Space optimization: don't inline this frequently instantiated fragment
2021-01-14 18:34:32 +00:00
PYBIND11_NOINLINE unique_function_record make_function_record ( ) {
return unique_function_record ( new detail : : function_record ( ) ) ;
2016-09-10 06:28:37 +00:00
}
2016-01-17 21:36:41 +00:00
/// Special internal constructor for functors, lambda functions, etc.
2017-02-17 11:56:41 +00:00
template < typename Func , typename Return , typename . . . Args , typename . . . Extra >
void initialize ( Func & & f , Return ( * ) ( Args . . . ) , const Extra & . . . extra ) {
2017-07-02 10:52:00 +00:00
using namespace detail ;
2018-01-12 16:06:46 +00:00
struct capture { remove_reference_t < Func > f ; } ;
2015-07-26 14:33:49 +00:00
2016-01-17 21:36:41 +00:00
/* Store the function including any extra state it might have (e.g. a lambda capture object) */
2021-01-14 18:34:32 +00:00
// The unique_ptr makes sure nothing is leaked in case of an exception.
auto unique_rec = make_function_record ( ) ;
auto rec = unique_rec . get ( ) ;
2015-07-29 15:43:52 +00:00
2016-05-10 14:05:03 +00:00
/* Store the capture object directly in the function record if there is enough space */
2021-07-30 18:25:29 +00:00
if ( PYBIND11_SILENCE_MSVC_C4127 ( sizeof ( capture ) < = sizeof ( rec - > data ) ) ) {
2016-07-10 08:13:18 +00:00
/* Without these pragmas, GCC warns that there might not be
enough space to use the placement new operator . However , the
' if ' statement above ensures that this is the case . */
2021-04-14 18:01:27 +00:00
# if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
2016-07-07 20:11:42 +00:00
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wplacement-new"
# endif
2016-05-10 14:05:03 +00:00
new ( ( capture * ) & rec - > data ) capture { std : : forward < Func > ( f ) } ;
2021-04-14 18:01:27 +00:00
# if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
2016-07-07 20:11:42 +00:00
# pragma GCC diagnostic pop
# endif
2021-07-15 16:38:52 +00:00
# if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
# endif
// UB without std::launder, but without breaking ABI and/or
// a significant refactoring it's "impossible" to solve.
2021-08-31 01:48:33 +00:00
if ( ! std : : is_trivially_destructible < capture > : : value )
2021-07-15 16:38:52 +00:00
rec - > free_data = [ ] ( function_record * r ) {
auto data = PYBIND11_STD_LAUNDER ( ( capture * ) & r - > data ) ;
( void ) data ;
data - > ~ capture ( ) ;
} ;
# if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
# pragma GCC diagnostic pop
# endif
2016-05-10 14:05:03 +00:00
} else {
rec - > data [ 0 ] = new capture { std : : forward < Func > ( f ) } ;
2018-01-12 16:06:46 +00:00
rec - > free_data = [ ] ( function_record * r ) { delete ( ( capture * ) r - > data [ 0 ] ) ; } ;
2016-05-10 14:05:03 +00:00
}
2015-10-13 15:37:25 +00:00
2016-05-10 14:05:03 +00:00
/* Type casters for the function arguments and return value */
2018-01-12 16:06:46 +00:00
using cast_in = argument_loader < Args . . . > ;
using cast_out = make_caster <
conditional_t < std : : is_void < Return > : : value , void_type , Return >
2016-11-27 17:19:34 +00:00
> ;
2015-07-26 14:33:49 +00:00
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
static_assert ( expected_num_args < Extra . . . > ( sizeof . . . ( Args ) , cast_in : : args_pos > = 0 , cast_in : : has_kwargs ) ,
2017-03-19 15:36:18 +00:00
" The number of argument annotations does not match the number of function arguments " ) ;
2017-01-22 04:42:14 +00:00
2016-01-17 21:36:41 +00:00
/* Dispatch code which converts function arguments and performs the actual function call */
2018-01-12 16:06:46 +00:00
rec - > impl = [ ] ( function_call & call ) - > handle {
2016-05-10 14:05:03 +00:00
cast_in args_converter ;
2016-01-17 21:36:41 +00:00
/* Try to cast the function arguments into the C++ domain */
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
if ( ! args_converter . load_args ( call ) )
2016-01-17 21:36:41 +00:00
return PYBIND11_TRY_NEXT_OVERLOAD ;
2016-01-17 21:36:44 +00:00
/* Invoke call policy pre-call hook */
2018-01-12 16:06:46 +00:00
process_attributes < Extra . . . > : : precall ( call ) ;
2016-05-10 14:05:03 +00:00
/* Get a pointer to the capture object */
2017-02-08 22:43:08 +00:00
auto data = ( sizeof ( capture ) < = sizeof ( call . func . data )
? & call . func . data : call . func . data [ 0 ] ) ;
2020-09-11 03:20:47 +00:00
auto * cap = const_cast < capture * > ( reinterpret_cast < const capture * > ( data ) ) ;
2016-01-17 21:36:41 +00:00
Add an ability to avoid forcing rvp::move
Eigen::Ref objects, when returned, are almost always returned as
rvalues; what's important is the data they reference, not the outer
shell, and so we want to be able to use `::copy`,
`::reference_internal`, etc. to refer to the data the Eigen::Ref
references (in the following commits), rather than the Eigen::Ref
instance itself.
This moves the policy override into a struct so that code that wants to
avoid it (or wants to provide some other Return-type-conditional
override) can create a specialization of
return_value_policy_override<Return> in order to override the override.
This lets an Eigen::Ref-returning function be bound with `rvp::copy`,
for example, to specify that the data should be copied into a new numpy
array rather than referenced, or `rvp::reference_internal` to indicate
that it should be referenced, but a keep-alive used (actually, we used
the array's `base` rather than a py::keep_alive in such a case, but it
accomplishes the same thing).
2017-01-20 05:59:26 +00:00
/* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
2018-07-17 14:56:26 +00:00
return_value_policy policy = return_value_policy_override < Return > : : policy ( call . func . policy ) ;
2016-11-20 04:31:02 +00:00
2017-03-16 10:22:26 +00:00
/* Function scope guard -- defaults to the compile-to-nothing `void_type` */
2018-01-12 16:06:46 +00:00
using Guard = extract_guard_t < Extra . . . > ;
2017-03-16 10:22:26 +00:00
2016-07-10 08:13:18 +00:00
/* Perform the function call */
2017-05-14 19:57:26 +00:00
handle result = cast_out : : cast (
std : : move ( args_converter ) . template call < Return , Guard > ( cap - > f ) , policy , call . parent ) ;
2016-01-17 21:36:44 +00:00
/* Invoke call policy post-call hook */
2018-01-12 16:06:46 +00:00
process_attributes < Extra . . . > : : postcall ( call , result ) ;
2016-01-17 21:36:41 +00:00
2016-01-17 21:36:39 +00:00
return result ;
2015-07-26 14:33:49 +00:00
} ;
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
rec - > nargs_pos = cast_in : : args_pos > = 0
? static_cast < std : : uint16_t > ( cast_in : : args_pos )
: sizeof . . . ( Args ) - cast_in : : has_kwargs ; // Will get reduced more if we have a kw_only
rec - > has_args = cast_in : : args_pos > = 0 ;
rec - > has_kwargs = cast_in : : has_kwargs ;
2016-01-17 21:36:44 +00:00
/* Process any user-provided function attributes */
2018-01-12 16:06:46 +00:00
process_attributes < Extra . . . > : : init ( extra . . . , rec ) ;
2016-01-17 21:36:41 +00:00
2017-12-23 22:56:07 +00:00
{
2020-09-05 00:02:05 +00:00
constexpr bool has_kw_only_args = any_of < std : : is_same < kw_only , Extra > . . . > : : value ,
has_pos_only_args = any_of < std : : is_same < pos_only , Extra > . . . > : : value ,
2017-12-23 22:56:07 +00:00
has_arg_annotations = any_of < is_keyword < Extra > . . . > : : value ;
2020-09-05 00:02:05 +00:00
static_assert ( has_arg_annotations | | ! has_kw_only_args , " py::kw_only requires the use of argument annotations " ) ;
static_assert ( has_arg_annotations | | ! has_pos_only_args , " py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument) " ) ;
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
static_assert ( constexpr_sum ( is_kw_only < Extra > : : value . . . ) < = 1 , " py::kw_only may be specified only once " ) ;
static_assert ( constexpr_sum ( is_pos_only < Extra > : : value . . . ) < = 1 , " py::pos_only may be specified only once " ) ;
constexpr auto kw_only_pos = constexpr_first < is_kw_only , Extra . . . > ( ) ;
constexpr auto pos_only_pos = constexpr_first < is_pos_only , Extra . . . > ( ) ;
static_assert ( ! ( has_kw_only_args & & has_pos_only_args ) | | pos_only_pos < kw_only_pos , " py::pos_only must come before py::kw_only " ) ;
2017-12-23 22:56:07 +00:00
}
2016-01-17 21:36:41 +00:00
/* Generate a readable signature describing the function's arguments and return value types */
2021-12-21 19:24:21 +00:00
static constexpr auto signature = const_name ( " ( " ) + cast_in : : arg_names + const_name ( " ) -> " ) + cast_out : : name ;
2017-07-02 10:52:00 +00:00
PYBIND11_DESCR_CONSTEXPR auto types = decltype ( signature ) : : types ( ) ;
2016-01-17 21:36:41 +00:00
/* Register the function with Python from generic (non-templated) code */
2021-01-14 18:34:32 +00:00
// Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
initialize_generic ( std : : move ( unique_rec ) , signature . text , types . data ( ) , sizeof . . . ( Args ) ) ;
2016-05-10 14:59:01 +00:00
2016-07-10 08:13:18 +00:00
/* Stash some additional information used by an important optimization in 'functional.h' */
2017-02-17 11:56:41 +00:00
using FunctionType = Return ( * ) ( Args . . . ) ;
2016-07-10 08:13:18 +00:00
constexpr bool is_function_ptr =
std : : is_convertible < Func , FunctionType > : : value & &
sizeof ( capture ) = = sizeof ( void * ) ;
if ( is_function_ptr ) {
rec - > is_stateless = true ;
2017-02-08 22:43:08 +00:00
rec - > data [ 1 ] = const_cast < void * > ( reinterpret_cast < const void * > ( & typeid ( FunctionType ) ) ) ;
2016-07-10 08:13:18 +00:00
}
2015-07-30 13:29:00 +00:00
}
2021-01-14 18:34:32 +00:00
// Utility class that keeps track of all duplicated strings, and cleans them up in its destructor,
// unless they are released. Basically a RAII-solution to deal with exceptions along the way.
class strdup_guard {
public :
~ strdup_guard ( ) {
for ( auto s : strings )
std : : free ( s ) ;
}
char * operator ( ) ( const char * s ) {
2021-07-26 18:28:36 +00:00
auto t = PYBIND11_COMPAT_STRDUP ( s ) ;
2021-01-14 18:34:32 +00:00
strings . push_back ( t ) ;
return t ;
}
void release ( ) {
strings . clear ( ) ;
}
private :
std : : vector < char * > strings ;
} ;
2016-01-17 21:36:41 +00:00
/// Register a function call with Python (generic non-templated code goes here)
2021-01-14 18:34:32 +00:00
void initialize_generic ( unique_function_record & & unique_rec , const char * text ,
2016-07-31 18:03:18 +00:00
const std : : type_info * const * types , size_t args ) {
2021-01-14 18:34:32 +00:00
// Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
// we do not want this to destuct the pointer. `initialize` (the caller) still relies on the
// pointee being alive after this call. Only move out if a `capsule` is going to keep it alive.
auto rec = unique_rec . get ( ) ;
// Keep track of strdup'ed strings, and clean them up as long as the function's capsule
// has not taken ownership yet (when `unique_rec.release()` is called).
// Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the strings
// are only referenced before strdup'ing. So only *after* the following block could `destruct`
// safely be called, but even then, `repr` could still throw in the middle of copying all strings.
strdup_guard guarded_strdup ;
2016-01-17 21:36:44 +00:00
2016-01-17 21:36:36 +00:00
/* Create copies of all referenced C-style strings */
2021-01-14 18:34:32 +00:00
rec - > name = guarded_strdup ( rec - > name ? rec - > name : " " ) ;
if ( rec - > doc ) rec - > doc = guarded_strdup ( rec - > doc ) ;
2016-01-17 21:36:44 +00:00
for ( auto & a : rec - > args ) {
2016-01-17 21:36:36 +00:00
if ( a . name )
2021-01-14 18:34:32 +00:00
a . name = guarded_strdup ( a . name ) ;
2016-01-17 21:36:36 +00:00
if ( a . descr )
2021-01-14 18:34:32 +00:00
a . descr = guarded_strdup ( a . descr ) ;
2016-01-17 21:36:36 +00:00
else if ( a . value )
2021-01-14 18:34:32 +00:00
a . descr = guarded_strdup ( repr ( a . value ) . cast < std : : string > ( ) . c_str ( ) ) ;
2016-01-17 21:36:36 +00:00
}
2016-07-10 08:13:18 +00:00
2022-01-11 22:57:59 +00:00
rec - > is_constructor = ( std : : strcmp ( rec - > name , " __init__ " ) = = 0 )
| | ( std : : strcmp ( rec - > name , " __setstate__ " ) = = 0 ) ;
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
2017-08-24 00:46:07 +00:00
# if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
if ( rec - > is_constructor & & ! rec - > is_new_style_constructor ) {
2020-10-02 02:57:25 +00:00
const auto class_name = detail : : get_fully_qualified_tp_name ( ( PyTypeObject * ) rec - > scope . ptr ( ) ) ;
2017-08-24 00:46:07 +00:00
const auto func_name = std : : string ( rec - > name ) ;
PyErr_WarnEx (
PyExc_FutureWarning ,
( " pybind11-bound class ' " + class_name + " ' is using an old-style "
" placement-new ' " + func_name + " ' which has been deprecated. See "
" the upgrade guide in pybind11's docs. This message is only visible "
" when compiled in debug mode. " ) . c_str ( ) , 0
) ;
}
# endif
2016-01-17 21:36:36 +00:00
/* Generate a proper function signature */
std : : string signature ;
2017-08-31 12:38:23 +00:00
size_t type_index = 0 , arg_index = 0 ;
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
bool is_starred = false ;
2017-08-31 12:38:23 +00:00
for ( auto * pc = text ; * pc ! = ' \0 ' ; + + pc ) {
const auto c = * pc ;
2016-01-17 21:36:36 +00:00
if ( c = = ' { ' ) {
2017-08-31 12:38:23 +00:00
// Write arg name for everything except *args and **kwargs.
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
is_starred = * ( pc + 1 ) = = ' * ' ;
if ( is_starred )
2017-08-31 12:38:23 +00:00
continue ;
2020-09-05 00:02:05 +00:00
// Separator for keyword-only arguments, placed before the kw
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
// arguments start (unless we are already putting an *args)
if ( ! rec - > has_args & & arg_index = = rec - > nargs_pos )
2020-09-05 00:02:05 +00:00
signature + = " *, " ;
2017-08-31 12:38:23 +00:00
if ( arg_index < rec - > args . size ( ) & & rec - > args [ arg_index ] . name ) {
signature + = rec - > args [ arg_index ] . name ;
} else if ( arg_index = = 0 & & rec - > is_method ) {
signature + = " self " ;
} else {
signature + = " arg " + std : : to_string ( arg_index - ( rec - > is_method ? 1 : 0 ) ) ;
2016-01-17 21:36:36 +00:00
}
2017-08-31 12:38:23 +00:00
signature + = " : " ;
2016-01-17 21:36:36 +00:00
} else if ( c = = ' } ' ) {
2017-08-31 12:38:23 +00:00
// Write default value if available.
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
if ( ! is_starred & & arg_index < rec - > args . size ( ) & & rec - > args [ arg_index ] . descr ) {
2017-11-27 04:00:35 +00:00
signature + = " = " ;
2017-08-31 12:38:23 +00:00
signature + = rec - > args [ arg_index ] . descr ;
2016-01-17 21:36:36 +00:00
}
2020-09-05 00:02:05 +00:00
// Separator for positional-only arguments (placed after the
// argument, rather than before like *
if ( rec - > nargs_pos_only > 0 & & ( arg_index + 1 ) = = rec - > nargs_pos_only )
signature + = " , / " ;
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
if ( ! is_starred )
arg_index + + ;
2016-01-17 21:36:36 +00:00
} else if ( c = = ' % ' ) {
const std : : type_info * t = types [ type_index + + ] ;
2016-01-17 21:36:40 +00:00
if ( ! t )
2016-01-17 21:36:41 +00:00
pybind11_fail ( " Internal error while parsing type signature (1) " ) ;
2016-10-23 14:43:03 +00:00
if ( auto tinfo = detail : : get_type_info ( * t ) ) {
2017-11-07 16:33:05 +00:00
handle th ( ( PyObject * ) tinfo - > type ) ;
signature + =
th . attr ( " __module__ " ) . cast < std : : string > ( ) + " . " +
th . attr ( " __qualname__ " ) . cast < std : : string > ( ) ; // Python 3.3+, but we backport it to earlier versions
2017-08-17 00:01:32 +00:00
} else if ( rec - > is_new_style_constructor & & arg_index = = 0 ) {
// A new-style `__init__` takes `self` as `value_and_holder`.
// Rewrite it to the proper class type.
2017-11-07 16:33:05 +00:00
signature + =
rec - > scope . attr ( " __module__ " ) . cast < std : : string > ( ) + " . " +
rec - > scope . attr ( " __qualname__ " ) . cast < std : : string > ( ) ;
2016-01-17 21:36:36 +00:00
} else {
std : : string tname ( t - > name ( ) ) ;
detail : : clean_type_id ( tname ) ;
signature + = tname ;
}
} else {
signature + = c ;
}
}
2020-09-05 00:02:05 +00:00
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
if ( arg_index ! = args - rec - > has_args - rec - > has_kwargs | | types [ type_index ] ! = nullptr )
2016-01-17 21:36:41 +00:00
pybind11_fail ( " Internal error while parsing type signature (2) " ) ;
2016-01-17 21:36:36 +00:00
2015-09-04 21:42:12 +00:00
# if PY_MAJOR_VERSION < 3
2022-01-11 22:57:59 +00:00
if ( std : : strcmp ( rec - > name , " __next__ " ) = = 0 ) {
2016-01-17 21:36:44 +00:00
std : : free ( rec - > name ) ;
2021-01-14 18:34:32 +00:00
rec - > name = guarded_strdup ( " next " ) ;
2022-01-11 22:57:59 +00:00
} else if ( std : : strcmp ( rec - > name , " __bool__ " ) = = 0 ) {
2016-05-16 16:52:46 +00:00
std : : free ( rec - > name ) ;
2021-01-14 18:34:32 +00:00
rec - > name = guarded_strdup ( " __nonzero__ " ) ;
2016-01-17 21:36:36 +00:00
}
2015-09-04 21:42:12 +00:00
# endif
2021-01-14 18:34:32 +00:00
rec - > signature = guarded_strdup ( signature . c_str ( ) ) ;
2016-01-17 21:36:44 +00:00
rec - > args . shrink_to_fit ( ) ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
rec - > nargs = ( std : : uint16_t ) args ;
2015-09-04 21:42:12 +00:00
2017-04-17 00:30:52 +00:00
if ( rec - > sibling & & PYBIND11_INSTANCE_METHOD_CHECK ( rec - > sibling . ptr ( ) ) )
rec - > sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION ( rec - > sibling . ptr ( ) ) ;
2015-07-29 15:43:52 +00:00
2016-01-17 21:36:44 +00:00
detail : : function_record * chain = nullptr , * chain_start = rec ;
2016-10-25 01:58:22 +00:00
if ( rec - > sibling ) {
if ( PyCFunction_Check ( rec - > sibling . ptr ( ) ) ) {
2021-09-20 14:42:14 +00:00
auto * self = PyCFunction_GET_SELF ( rec - > sibling . ptr ( ) ) ;
capsule rec_capsule = isinstance < capsule > ( self ) ? reinterpret_borrow < capsule > ( self ) : capsule ( self ) ;
2016-10-25 01:58:22 +00:00
chain = ( detail : : function_record * ) rec_capsule ;
/* Never append a method to an overload chain of a parent class;
instead , hide the parent ' s overloads in this case */
2017-02-08 00:01:56 +00:00
if ( ! chain - > scope . is ( rec - > scope ) )
2016-10-25 01:58:22 +00:00
chain = nullptr ;
}
// Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
else if ( ! rec - > sibling . is_none ( ) & & rec - > name [ 0 ] ! = ' _ ' )
pybind11_fail ( " Cannot overload existing non-function object \" " + std : : string ( rec - > name ) +
" \" with a function of the same name " ) ;
2015-10-01 14:46:03 +00:00
}
2016-01-17 21:36:44 +00:00
if ( ! chain ) {
2016-01-17 21:36:41 +00:00
/* No existing overload was found, create a new function object */
2016-01-17 21:36:44 +00:00
rec - > def = new PyMethodDef ( ) ;
2017-02-23 02:36:09 +00:00
std : : memset ( rec - > def , 0 , sizeof ( PyMethodDef ) ) ;
2016-01-17 21:36:44 +00:00
rec - > def - > ml_name = rec - > name ;
2021-06-21 14:37:48 +00:00
rec - > def - > ml_meth
2021-07-09 13:45:53 +00:00
= reinterpret_cast < PyCFunction > ( reinterpret_cast < void ( * ) ( ) > ( dispatcher ) ) ;
2016-01-17 21:36:44 +00:00
rec - > def - > ml_flags = METH_VARARGS | METH_KEYWORDS ;
2016-02-04 22:02:07 +00:00
2021-01-14 18:34:32 +00:00
capsule rec_capsule ( unique_rec . release ( ) , [ ] ( void * ptr ) {
2017-03-22 21:04:00 +00:00
destruct ( ( detail : : function_record * ) ptr ) ;
2016-01-17 21:36:41 +00:00
} ) ;
2021-01-14 18:34:32 +00:00
guarded_strdup . release ( ) ;
2016-02-04 22:02:07 +00:00
object scope_module ;
if ( rec - > scope ) {
2016-09-20 23:06:32 +00:00
if ( hasattr ( rec - > scope , " __module__ " ) ) {
scope_module = rec - > scope . attr ( " __module__ " ) ;
} else if ( hasattr ( rec - > scope , " __name__ " ) ) {
scope_module = rec - > scope . attr ( " __name__ " ) ;
}
2016-02-04 22:02:07 +00:00
}
m_ptr = PyCFunction_NewEx ( rec - > def , rec_capsule . ptr ( ) , scope_module . ptr ( ) ) ;
2015-07-05 18:05:44 +00:00
if ( ! m_ptr )
2016-01-17 21:36:41 +00:00
pybind11_fail ( " cpp_function::cpp_function(): Could not allocate function object " ) ;
2015-07-05 18:05:44 +00:00
} else {
2020-10-06 02:36:33 +00:00
/* Append at the beginning or end of the overload chain */
2016-01-17 21:36:44 +00:00
m_ptr = rec - > sibling . ptr ( ) ;
2015-07-05 18:05:44 +00:00
inc_ref ( ) ;
2017-04-17 02:31:13 +00:00
if ( chain - > is_method ! = rec - > is_method )
pybind11_fail ( " overloading a method with both static and instance methods is not supported; "
# if defined(NDEBUG)
" compile in debug mode for more details "
# else
" error while attempting to bind " + std : : string ( rec - > is_method ? " instance " : " static " ) + " method " +
std : : string ( pybind11 : : str ( rec - > scope . attr ( " __name__ " ) ) ) + " . " + std : : string ( rec - > name ) + signature
# endif
) ;
2020-10-06 02:36:33 +00:00
if ( rec - > prepend ) {
// Beginning of chain; we need to replace the capsule's current head-of-the-chain
// pointer with this one, then make this one point to the previous head of the
// chain.
chain_start = rec ;
rec - > next = chain ;
auto rec_capsule = reinterpret_borrow < capsule > ( ( ( PyCFunctionObject * ) m_ptr ) - > m_self ) ;
2021-01-14 18:34:32 +00:00
rec_capsule . set_pointer ( unique_rec . release ( ) ) ;
guarded_strdup . release ( ) ;
2020-10-06 02:36:33 +00:00
} else {
// Or end of chain (normal behavior)
chain_start = chain ;
while ( chain - > next )
chain = chain - > next ;
2021-01-14 18:34:32 +00:00
chain - > next = unique_rec . release ( ) ;
guarded_strdup . release ( ) ;
2020-10-06 02:36:33 +00:00
}
2015-07-05 18:05:44 +00:00
}
2015-07-30 13:29:00 +00:00
2015-07-05 18:05:44 +00:00
std : : string signatures ;
2015-07-29 15:43:52 +00:00
int index = 0 ;
2016-01-17 21:36:44 +00:00
/* Create a nice pydoc rec including all signatures and
2016-01-17 21:36:41 +00:00
docstrings of the functions in the overload chain */
2016-11-15 11:38:05 +00:00
if ( chain & & options : : show_function_signatures ( ) ) {
2016-03-08 21:42:12 +00:00
// First a generic signature
signatures + = rec - > name ;
signatures + = " (*args, **kwargs) \n " ;
signatures + = " Overloaded function. \n \n " ;
}
// Then specific overload signatures
2017-03-08 17:32:42 +00:00
bool first_user_def = true ;
2016-01-17 21:36:44 +00:00
for ( auto it = chain_start ; it ! = nullptr ; it = it - > next ) {
2016-11-15 11:38:05 +00:00
if ( options : : show_function_signatures ( ) ) {
2017-03-08 17:32:42 +00:00
if ( index > 0 ) signatures + = " \n " ;
2016-11-15 11:38:05 +00:00
if ( chain )
signatures + = std : : to_string ( + + index ) + " . " ;
signatures + = rec - > name ;
signatures + = it - > signature ;
2016-01-17 21:36:36 +00:00
signatures + = " \n " ;
2016-11-15 11:38:05 +00:00
}
2021-07-01 06:35:25 +00:00
if ( it - > doc & & it - > doc [ 0 ] ! = ' \0 ' & & options : : show_user_defined_docstrings ( ) ) {
2017-03-08 17:32:42 +00:00
// If we're appending another docstring, and aren't printing function signatures, we
// need to append a newline first:
if ( ! options : : show_function_signatures ( ) ) {
if ( first_user_def ) first_user_def = false ;
else signatures + = " \n " ;
}
2016-11-15 11:38:05 +00:00
if ( options : : show_function_signatures ( ) ) signatures + = " \n " ;
2016-02-28 22:52:37 +00:00
signatures + = it - > doc ;
2016-11-15 11:38:05 +00:00
if ( options : : show_function_signatures ( ) ) signatures + = " \n " ;
2016-01-17 21:36:36 +00:00
}
2015-07-05 18:05:44 +00:00
}
2016-01-17 21:36:44 +00:00
/* Install docstring */
2020-09-11 03:20:47 +00:00
auto * func = ( PyCFunctionObject * ) m_ptr ;
2020-12-28 03:56:30 +00:00
std : : free ( const_cast < char * > ( func - > m_ml - > ml_doc ) ) ;
// Install docstring if it's non-empty (when at least one option is enabled)
2021-07-26 18:28:36 +00:00
func - > m_ml - > ml_doc
= signatures . empty ( ) ? nullptr : PYBIND11_COMPAT_STRDUP ( signatures . c_str ( ) ) ;
2016-01-17 21:36:44 +00:00
2016-11-20 04:27:05 +00:00
if ( rec - > is_method ) {
m_ptr = PYBIND11_INSTANCE_METHOD_NEW ( m_ptr , rec - > scope . ptr ( ) ) ;
2015-07-05 18:05:44 +00:00
if ( ! m_ptr )
2016-01-17 21:36:41 +00:00
pybind11_fail ( " cpp_function::cpp_function(): Could not allocate instance method object " ) ;
2015-07-05 18:05:44 +00:00
Py_DECREF ( func ) ;
}
}
2016-01-17 21:36:44 +00:00
/// When a cpp_function is GCed, release any memory allocated by pybind11
2021-01-14 18:34:32 +00:00
static void destruct ( detail : : function_record * rec , bool free_strings = true ) {
2020-10-14 18:11:09 +00:00
// If on Python 3.9, check the interpreter "MICRO" (patch) version.
// If this is running on 3.9.0, we have to work around a bug.
# if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
static bool is_zero = Py_GetVersion ( ) [ 4 ] = = ' 0 ' ;
# endif
2016-01-17 21:36:44 +00:00
while ( rec ) {
detail : : function_record * next = rec - > next ;
if ( rec - > free_data )
2016-05-10 14:05:03 +00:00
rec - > free_data ( rec ) ;
2021-01-14 18:34:32 +00:00
// During initialization, these strings might not have been copied yet,
// so they cannot be freed. Once the function has been created, they can.
// Check `make_function_record` for more details.
if ( free_strings ) {
std : : free ( ( char * ) rec - > name ) ;
std : : free ( ( char * ) rec - > doc ) ;
std : : free ( ( char * ) rec - > signature ) ;
for ( auto & arg : rec - > args ) {
std : : free ( const_cast < char * > ( arg . name ) ) ;
std : : free ( const_cast < char * > ( arg . descr ) ) ;
}
2016-01-17 21:36:44 +00:00
}
2021-01-14 18:34:32 +00:00
for ( auto & arg : rec - > args )
arg . value . dec_ref ( ) ;
2016-01-17 21:36:44 +00:00
if ( rec - > def ) {
2017-02-08 22:43:08 +00:00
std : : free ( const_cast < char * > ( rec - > def - > ml_doc ) ) ;
2020-10-14 18:11:09 +00:00
// Python 3.9.0 decref's these in the wrong order; rec->def
// If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
// See https://github.com/python/cpython/pull/22670
# if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
if ( ! is_zero )
delete rec - > def ;
# else
delete rec - > def ;
# endif
2016-01-17 21:36:44 +00:00
}
delete rec ;
rec = next ;
}
}
2021-07-21 12:22:18 +00:00
2016-01-17 21:36:44 +00:00
/// Main dispatch logic for calls to functions bound using pybind11
2017-01-22 04:42:14 +00:00
static PyObject * dispatcher ( PyObject * self , PyObject * args_in , PyObject * kwargs_in ) {
2017-01-30 18:34:38 +00:00
using namespace detail ;
2016-01-17 21:36:44 +00:00
/* Iterator over the list of potentially admissible overloads */
2018-09-25 21:55:18 +00:00
const function_record * overloads = ( function_record * ) PyCapsule_GetPointer ( self , nullptr ) ,
* it = overloads ;
2016-01-17 21:36:44 +00:00
/* Need to know how many arguments + keyword arguments there are to pick the right overload */
2020-09-11 03:20:47 +00:00
const auto n_args_in = ( size_t ) PyTuple_GET_SIZE ( args_in ) ;
2016-01-17 21:36:44 +00:00
2017-01-22 04:42:14 +00:00
handle parent = n_args_in > 0 ? PyTuple_GET_ITEM ( args_in , 0 ) : nullptr ,
2016-01-17 21:36:44 +00:00
result = PYBIND11_TRY_NEXT_OVERLOAD ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
2017-08-17 00:01:32 +00:00
auto self_value_and_holder = value_and_holder ( ) ;
if ( overloads - > is_constructor ) {
2021-04-02 17:13:44 +00:00
if ( ! parent | | ! PyObject_TypeCheck ( parent . ptr ( ) , ( PyTypeObject * ) overloads - > scope . ptr ( ) ) ) {
PyErr_SetString ( PyExc_TypeError , " __init__(self, ...) called with invalid or missing `self` argument " ) ;
2017-08-17 00:01:32 +00:00
return nullptr ;
}
2020-12-31 16:10:11 +00:00
const auto tinfo = get_type_info ( ( PyTypeObject * ) overloads - > scope . ptr ( ) ) ;
const auto pi = reinterpret_cast < instance * > ( parent . ptr ( ) ) ;
self_value_and_holder = pi - > get_value_and_holder ( tinfo , true ) ;
2017-08-17 00:01:32 +00:00
// If this value is already registered it must mean __init__ is invoked multiple times;
// we really can't support that in C++, so just ignore the second __init__.
if ( self_value_and_holder . instance_registered ( ) )
return none ( ) . release ( ) . ptr ( ) ;
}
2016-01-17 21:36:44 +00:00
try {
2017-02-03 23:25:34 +00:00
// We do this in two passes: in the first pass, we load arguments with `convert=false`;
// in the second, we allow conversion (except for arguments with an explicit
// py::arg().noconvert()). This lets us prefer calls without conversion, with
// conversion as a fallback.
std : : vector < function_call > second_pass ;
// However, if there are no overloads, we can just skip the no-convert pass entirely
const bool overloaded = it ! = nullptr & & it - > next ! = nullptr ;
2016-01-17 21:36:44 +00:00
for ( ; it ! = nullptr ; it = it - > next ) {
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
2016-01-17 21:36:44 +00:00
/* For each overload:
2017-01-22 04:42:14 +00:00
1. Copy all positional arguments we were given , also checking to make sure that
named positional arguments weren ' t * also * specified via kwarg .
2017-01-31 16:23:53 +00:00
2. If we weren ' t given enough , try to make up the omitted ones by checking
2017-01-22 04:42:14 +00:00
whether they were provided by a kwarg matching the ` py : : arg ( " name " ) ` name . If
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
so , use it ( and remove it from kwargs ) ; if not , see if the function binding
2017-01-22 04:42:14 +00:00
provided a default that we can use .
3. Ensure that either all keyword arguments were " consumed " , or that the function
takes a kwargs argument to accept unconsumed kwargs .
4. Any positional arguments still left get put into a tuple ( for args ) , and any
leftover kwargs get put into a dict .
5. Pack everything into a vector ; if we have py : : args or py : : kwargs , they are an
extra tuple or dict at the end of the positional arguments .
6. Call the function call dispatcher ( function_record : : impl )
If one of these fail , move on to the next overload and keep trying until we get a
result other than PYBIND11_TRY_NEXT_OVERLOAD .
2016-01-17 21:36:44 +00:00
*/
2018-09-25 21:55:18 +00:00
const function_record & func = * it ;
2017-12-23 22:56:07 +00:00
size_t num_args = func . nargs ; // Number of positional arguments that we need
if ( func . has_args ) - - num_args ; // (but don't count py::args
if ( func . has_kwargs ) - - num_args ; // or py::kwargs)
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
size_t pos_args = func . nargs_pos ;
2016-01-17 21:36:44 +00:00
2017-01-30 18:34:38 +00:00
if ( ! func . has_args & & n_args_in > pos_args )
2017-12-23 22:56:07 +00:00
continue ; // Too many positional arguments for this overload
2017-01-22 04:42:14 +00:00
2017-01-30 18:34:38 +00:00
if ( n_args_in < pos_args & & func . args . size ( ) < pos_args )
2017-12-23 22:56:07 +00:00
continue ; // Not enough positional arguments given, and not enough defaults to fill in the blanks
2017-01-22 04:42:14 +00:00
2017-01-30 18:34:38 +00:00
function_call call ( func , parent ) ;
2016-01-17 21:36:44 +00:00
2019-07-18 07:01:50 +00:00
size_t args_to_copy = ( std : : min ) ( pos_args , n_args_in ) ; // Protect std::min with parentheses
2017-01-22 04:42:14 +00:00
size_t args_copied = 0 ;
2017-08-17 00:01:32 +00:00
// 0. Inject new-style `self` argument
if ( func . is_new_style_constructor ) {
// The `value` may have been preallocated by an old-style `__init__`
// if it was a preceding candidate for overload resolution.
if ( self_value_and_holder )
self_value_and_holder . type - > dealloc ( self_value_and_holder ) ;
2017-09-04 11:49:19 +00:00
call . init_self = PyTuple_GET_ITEM ( args_in , 0 ) ;
2020-09-11 03:26:50 +00:00
call . args . emplace_back ( reinterpret_cast < PyObject * > ( & self_value_and_holder ) ) ;
2017-08-17 00:01:32 +00:00
call . args_convert . push_back ( false ) ;
+ + args_copied ;
}
2017-01-22 04:42:14 +00:00
// 1. Copy any position arguments given.
2017-05-17 15:55:43 +00:00
bool bad_arg = false ;
2017-01-22 04:42:14 +00:00
for ( ; args_copied < args_to_copy ; + + args_copied ) {
2018-09-25 21:55:18 +00:00
const argument_record * arg_rec = args_copied < func . args . size ( ) ? & func . args [ args_copied ] : nullptr ;
2021-07-02 14:02:33 +00:00
if ( kwargs_in & & arg_rec & & arg_rec - > name & & dict_getitemstring ( kwargs_in , arg_rec - > name ) ) {
2017-05-17 15:55:43 +00:00
bad_arg = true ;
2017-02-24 00:54:53 +00:00
break ;
2017-01-22 04:42:14 +00:00
}
2017-05-17 15:55:43 +00:00
handle arg ( PyTuple_GET_ITEM ( args_in , args_copied ) ) ;
if ( arg_rec & & ! arg_rec - > none & & arg . is_none ( ) ) {
bad_arg = true ;
break ;
}
call . args . push_back ( arg ) ;
call . args_convert . push_back ( arg_rec ? arg_rec - > convert : true ) ;
2017-01-22 04:42:14 +00:00
}
2017-05-17 15:55:43 +00:00
if ( bad_arg )
2017-02-24 00:54:53 +00:00
continue ; // Maybe it was meant for another overload (issue #688)
2017-01-22 04:42:14 +00:00
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
// Keep track of how many position args we copied out in case we need to come back
// to copy the rest into a py::args argument.
size_t positional_args_copied = args_copied ;
2017-01-22 04:42:14 +00:00
// We'll need to copy this if we steal some kwargs for defaults
dict kwargs = reinterpret_borrow < dict > ( kwargs_in ) ;
2020-09-05 00:02:05 +00:00
// 1.5. Fill in any missing pos_only args from defaults if they exist
if ( args_copied < func . nargs_pos_only ) {
for ( ; args_copied < func . nargs_pos_only ; + + args_copied ) {
2020-10-20 21:57:22 +00:00
const auto & arg_rec = func . args [ args_copied ] ;
2020-09-05 00:02:05 +00:00
handle value ;
2020-10-20 21:57:22 +00:00
if ( arg_rec . value ) {
value = arg_rec . value ;
2020-09-05 00:02:05 +00:00
}
if ( value ) {
call . args . push_back ( value ) ;
2020-10-20 21:57:22 +00:00
call . args_convert . push_back ( arg_rec . convert ) ;
2020-09-05 00:02:05 +00:00
} else
break ;
}
if ( args_copied < func . nargs_pos_only )
continue ; // Not enough defaults to fill the positional arguments
}
2017-01-22 04:42:14 +00:00
// 2. Check kwargs and, failing that, defaults that may help complete the list
2017-12-23 22:56:07 +00:00
if ( args_copied < num_args ) {
2017-01-22 04:42:14 +00:00
bool copied_kwargs = false ;
2017-12-23 22:56:07 +00:00
for ( ; args_copied < num_args ; + + args_copied ) {
2020-10-20 21:57:22 +00:00
const auto & arg_rec = func . args [ args_copied ] ;
2017-01-22 04:42:14 +00:00
handle value ;
2020-10-20 21:57:22 +00:00
if ( kwargs_in & & arg_rec . name )
2021-07-02 14:02:33 +00:00
value = dict_getitemstring ( kwargs . ptr ( ) , arg_rec . name ) ;
2016-01-17 21:36:44 +00:00
if ( value ) {
2017-01-22 04:42:14 +00:00
// Consume a kwargs value
if ( ! copied_kwargs ) {
kwargs = reinterpret_steal < dict > ( PyDict_Copy ( kwargs . ptr ( ) ) ) ;
copied_kwargs = true ;
}
2021-07-02 14:02:33 +00:00
if ( PyDict_DelItemString ( kwargs . ptr ( ) , arg_rec . name ) = = - 1 ) {
throw error_already_set ( ) ;
}
2020-10-20 21:57:22 +00:00
} else if ( arg_rec . value ) {
value = arg_rec . value ;
}
if ( ! arg_rec . none & & value . is_none ( ) ) {
break ;
2017-01-22 04:42:14 +00:00
}
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
if ( value ) {
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
// If we're at the py::args index then first insert a stub for it to be replaced later
if ( func . has_args & & call . args . size ( ) = = func . nargs_pos )
call . args . push_back ( none ( ) ) ;
2017-01-30 18:34:38 +00:00
call . args . push_back ( value ) ;
2020-10-20 21:57:22 +00:00
call . args_convert . push_back ( arg_rec . convert ) ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
}
2017-01-22 04:42:14 +00:00
else
2016-01-17 21:36:44 +00:00
break ;
2017-01-22 04:42:14 +00:00
}
2017-12-23 22:56:07 +00:00
if ( args_copied < num_args )
2017-01-22 04:42:14 +00:00
continue ; // Not enough arguments, defaults, or kwargs to fill the positional arguments
}
// 3. Check everything was consumed (unless we have a kwargs arg)
2020-09-11 02:49:33 +00:00
if ( kwargs & & ! kwargs . empty ( ) & & ! func . has_kwargs )
2017-01-22 04:42:14 +00:00
continue ; // Unconsumed kwargs, but no py::kwargs argument to accept them
// 4a. If we have a py::args argument, create a new tuple with leftovers
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
if ( func . has_args ) {
2017-12-23 13:42:32 +00:00
tuple extra_args ;
2017-01-22 04:42:14 +00:00
if ( args_to_copy = = 0 ) {
// We didn't copy out any position arguments from the args_in tuple, so we
// can reuse it directly without copying:
extra_args = reinterpret_borrow < tuple > ( args_in ) ;
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
} else if ( positional_args_copied > = n_args_in ) {
2017-01-22 04:42:14 +00:00
extra_args = tuple ( 0 ) ;
2017-01-31 16:23:53 +00:00
} else {
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
size_t args_size = n_args_in - positional_args_copied ;
2017-01-22 04:42:14 +00:00
extra_args = tuple ( args_size ) ;
for ( size_t i = 0 ; i < args_size ; + + i ) {
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
extra_args [ i ] = PyTuple_GET_ITEM ( args_in , positional_args_copied + i ) ;
2016-01-17 21:36:44 +00:00
}
}
feat: allow kw-only args after a py::args (#3402)
* Simply has_kw_only_args handling
This simplifies tracking the number of kw-only args by instead tracking
the number of positional arguments (which is really what we care about
everywhere this is used).
* Allow keyword-only arguments to follow py::args
This removes the constraint that py::args has to be last (or
second-last, with py::kwargs) and instead makes py::args imply
py::kw_only for any remaining arguments, allowing you to bind a function
that works the same way as a Python function such as:
def f(a, *args, b):
return a * b + sum(args)
f(10, 1, 2, 3, b=20) # == 206
With this change, you can bind such a function using:
m.def("f", [](int a, py::args args, int b) { /* ... */ },
"a"_a, "b"_a);
Or, to be more explicit about the keyword-only arguments:
m.def("g", [](int a, py::args args, int b) { /* ... */ },
"a"_a, py::kw_only{}, "b"_a);
(The only difference between the two is that the latter will fail at
binding time if the `kw_only{}` doesn't match the `py::args` position).
This doesn't affect backwards compatibility at all because, currently,
you can't have a py::args anywhere except the end/2nd-last.
* Take args/kwargs by const lvalue ref
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-10-29 03:16:55 +00:00
if ( call . args . size ( ) < = func . nargs_pos )
call . args . push_back ( extra_args ) ;
else
call . args [ func . nargs_pos ] = extra_args ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
call . args_convert . push_back ( false ) ;
2017-12-23 13:42:32 +00:00
call . args_ref = std : : move ( extra_args ) ;
2016-01-17 21:36:44 +00:00
}
2016-05-01 12:42:20 +00:00
2017-01-22 04:42:14 +00:00
// 4b. If we have a py::kwargs, pass on any remaining kwargs
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
if ( func . has_kwargs ) {
2017-01-22 04:42:14 +00:00
if ( ! kwargs . ptr ( ) )
kwargs = dict ( ) ; // If we didn't get one, send an empty one
2017-01-30 18:34:38 +00:00
call . args . push_back ( kwargs ) ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
call . args_convert . push_back ( false ) ;
2017-12-23 13:42:32 +00:00
call . kwargs_ref = std : : move ( kwargs ) ;
2017-01-22 04:42:14 +00:00
}
2017-01-30 18:34:38 +00:00
// 5. Put everything in a vector. Not technically step 5, we've been building it
// in `call.args` all along.
# if !defined(NDEBUG)
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
if ( call . args . size ( ) ! = func . nargs | | call . args_convert . size ( ) ! = func . nargs )
2017-01-30 18:34:38 +00:00
pybind11_fail ( " Internal error: function call dispatcher inserted wrong number of arguments! " ) ;
# endif
2017-01-22 04:42:14 +00:00
2017-02-03 23:25:34 +00:00
std : : vector < bool > second_pass_convert ;
if ( overloaded ) {
// We're in the first no-convert pass, so swap out the conversion flags for a
// set of all-false flags. If the call fails, we'll swap the flags back in for
// the conversion-allowed call below.
second_pass_convert . resize ( func . nargs , false ) ;
call . args_convert . swap ( second_pass_convert ) ;
}
2017-01-22 04:42:14 +00:00
// 6. Call the function.
2016-05-01 12:42:20 +00:00
try {
2017-06-26 18:34:06 +00:00
loader_life_support guard { } ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
result = func . impl ( call ) ;
2016-07-01 14:07:35 +00:00
} catch ( reference_cast_error & ) {
2016-05-01 12:42:20 +00:00
result = PYBIND11_TRY_NEXT_OVERLOAD ;
}
2016-01-17 21:36:44 +00:00
if ( result . ptr ( ) ! = PYBIND11_TRY_NEXT_OVERLOAD )
break ;
Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation. This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.
Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).
Specifying a noconvert looks like one of these:
m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting
(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).
Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument. Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-01-23 08:50:00 +00:00
2017-02-03 23:25:34 +00:00
if ( overloaded ) {
// The (overloaded) call failed; if the call has at least one argument that
// permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
// then add this call to the list of second pass overloads to try.
for ( size_t i = func . is_method ? 1 : 0 ; i < pos_args ; i + + ) {
if ( second_pass_convert [ i ] ) {
// Found one: swap the converting flags back in and store the call for
// the second pass.
call . args_convert . swap ( second_pass_convert ) ;
second_pass . push_back ( std : : move ( call ) ) ;
break ;
}
}
}
}
if ( overloaded & & ! second_pass . empty ( ) & & result . ptr ( ) = = PYBIND11_TRY_NEXT_OVERLOAD ) {
// The no-conversion pass finished without success, try again with conversion allowed
for ( auto & call : second_pass ) {
try {
2017-06-26 18:34:06 +00:00
loader_life_support guard { } ;
2017-02-03 23:25:34 +00:00
result = call . func . impl ( call ) ;
} catch ( reference_cast_error & ) {
result = PYBIND11_TRY_NEXT_OVERLOAD ;
}
2018-09-25 21:55:18 +00:00
if ( result . ptr ( ) ! = PYBIND11_TRY_NEXT_OVERLOAD ) {
// The error reporting logic below expects 'it' to be valid, as it would be
// if we'd encountered this failure in the first-pass loop.
if ( ! result )
it = & call . func ;
2017-02-03 23:25:34 +00:00
break ;
2018-09-25 21:55:18 +00:00
}
2017-02-03 23:25:34 +00:00
}
2016-01-17 21:36:44 +00:00
}
2016-09-10 09:58:02 +00:00
} catch ( error_already_set & e ) {
e . restore ( ) ;
2016-06-17 21:35:59 +00:00
return nullptr ;
2020-10-09 21:12:05 +00:00
# ifdef __GLIBCXX__
2019-06-10 20:00:55 +00:00
} catch ( abi : : __forced_unwind & ) {
throw ;
# endif
2016-01-17 21:36:44 +00:00
} catch ( . . . ) {
2016-06-17 21:35:59 +00:00
/* When an exception is caught, give each registered exception
2021-07-21 12:22:18 +00:00
translator a chance to translate it to a Python exception . First
all module - local translators will be tried in reverse order of
registration . If none of the module - locale translators handle
the exception ( or there are no module - locale translators ) then
the global translators will be tried , also in reverse order of
registration .
2016-07-18 08:47:10 +00:00
2016-06-17 21:35:59 +00:00
A translator may choose to do one of the following :
2016-07-18 08:47:10 +00:00
2016-06-17 21:35:59 +00:00
- catch the exception and call PyErr_SetString or PyErr_SetObject
to set a standard ( or custom ) Python exception , or
- do nothing and let the exception fall through to the next translator , or
- delegate translation to the next translator by throwing a new type of exception . */
2021-07-21 12:22:18 +00:00
auto & local_exception_translators = get_local_internals ( ) . registered_exception_translators ;
if ( detail : : apply_exception_translators ( local_exception_translators ) ) {
return nullptr ;
}
auto & exception_translators = get_internals ( ) . registered_exception_translators ;
if ( detail : : apply_exception_translators ( exception_translators ) ) {
2016-06-17 21:35:59 +00:00
return nullptr ;
}
2021-07-21 12:22:18 +00:00
2016-06-17 21:35:59 +00:00
PyErr_SetString ( PyExc_SystemError , " Exception escaped from default exception translator! " ) ;
2016-01-17 21:36:44 +00:00
return nullptr ;
}
2017-09-09 18:21:34 +00:00
auto append_note_if_missing_header_is_suspected = [ ] ( std : : string & msg ) {
if ( msg . find ( " std:: " ) ! = std : : string : : npos ) {
msg + = " \n \n "
" Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>, \n "
" <pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic \n "
" conversions are optional and require extra headers to be included \n "
" when compiling your pybind11 module. " ;
}
} ;
2016-01-17 21:36:44 +00:00
if ( result . ptr ( ) = = PYBIND11_TRY_NEXT_OVERLOAD ) {
2016-09-10 06:28:37 +00:00
if ( overloads - > is_operator )
return handle ( Py_NotImplemented ) . inc_ref ( ) . ptr ( ) ;
2016-09-12 02:44:37 +00:00
std : : string msg = std : : string ( overloads - > name ) + " (): incompatible " +
std : : string ( overloads - > is_constructor ? " constructor " : " function " ) +
" arguments. The following argument types are supported: \n " ;
2016-01-17 21:36:44 +00:00
int ctr = 0 ;
2018-09-25 21:55:18 +00:00
for ( const function_record * it2 = overloads ; it2 ! = nullptr ; it2 = it2 - > next ) {
2016-01-17 21:36:44 +00:00
msg + = " " + std : : to_string ( + + ctr ) + " . " ;
2016-07-17 21:43:00 +00:00
bool wrote_sig = false ;
if ( overloads - > is_constructor ) {
2016-07-31 18:03:18 +00:00
// For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
2016-07-17 21:43:00 +00:00
std : : string sig = it2 - > signature ;
2016-07-31 18:03:18 +00:00
size_t start = sig . find ( ' ( ' ) + 7 ; // skip "(self: "
2016-07-17 21:43:00 +00:00
if ( start < sig . size ( ) ) {
// End at the , for the next argument
size_t end = sig . find ( " , " ) , next = end + 2 ;
size_t ret = sig . rfind ( " -> " ) ;
// Or the ), if there is no comma:
if ( end > = sig . size ( ) ) next = end = sig . find ( ' ) ' ) ;
if ( start < end & & next < sig . size ( ) ) {
msg . append ( sig , start , end - start ) ;
msg + = ' ( ' ;
msg . append ( sig , next , ret - next ) ;
wrote_sig = true ;
}
}
}
if ( ! wrote_sig ) msg + = it2 - > signature ;
2016-01-17 21:36:44 +00:00
msg + = " \n " ;
}
2016-09-12 02:44:37 +00:00
msg + = " \n Invoked with: " ;
2017-01-22 04:42:14 +00:00
auto args_ = reinterpret_borrow < tuple > ( args_in ) ;
2017-02-24 02:04:46 +00:00
bool some_args = false ;
2016-07-18 08:47:10 +00:00
for ( size_t ti = overloads - > is_constructor ? 1 : 0 ; ti < args_ . size ( ) ; + + ti ) {
2017-02-24 02:04:46 +00:00
if ( ! some_args ) some_args = true ;
else msg + = " , " ;
2020-08-18 11:14:34 +00:00
try {
msg + = pybind11 : : repr ( args_ [ ti ] ) ;
} catch ( const error_already_set & ) {
msg + = " <repr raised Error> " ;
}
2016-05-24 07:19:35 +00:00
}
2017-02-24 02:04:46 +00:00
if ( kwargs_in ) {
auto kwargs = reinterpret_borrow < dict > ( kwargs_in ) ;
2020-09-11 02:49:33 +00:00
if ( ! kwargs . empty ( ) ) {
2017-02-24 02:04:46 +00:00
if ( some_args ) msg + = " ; " ;
msg + = " kwargs: " ;
bool first = true ;
for ( auto kwarg : kwargs ) {
if ( first ) first = false ;
else msg + = " , " ;
2020-08-18 11:14:34 +00:00
msg + = pybind11 : : str ( " {}= " ) . format ( kwarg . first ) ;
try {
msg + = pybind11 : : repr ( kwarg . second ) ;
} catch ( const error_already_set & ) {
msg + = " <repr raised Error> " ;
}
2017-02-24 02:04:46 +00:00
}
}
}
2017-09-09 18:21:34 +00:00
append_note_if_missing_header_is_suspected ( msg ) ;
2022-01-31 20:13:05 +00:00
# if PY_VERSION_HEX >= 0x03030000
// Attach additional error info to the exception if supported
if ( PyErr_Occurred ( ) ) {
raise_from ( PyExc_TypeError , msg . c_str ( ) ) ;
return nullptr ;
}
# endif
2016-01-17 21:36:44 +00:00
PyErr_SetString ( PyExc_TypeError , msg . c_str ( ) ) ;
return nullptr ;
2021-07-09 13:45:53 +00:00
}
if ( ! result ) {
2016-01-17 21:36:44 +00:00
std : : string msg = " Unable to convert function return value to a "
" Python type! The signature was \n \t " ;
msg + = it - > signature ;
2017-09-09 18:21:34 +00:00
append_note_if_missing_header_is_suspected ( msg ) ;
2022-01-11 02:18:00 +00:00
# if PY_VERSION_HEX >= 0x03030000
// Attach additional error info to the exception if supported
if ( PyErr_Occurred ( ) ) {
raise_from ( PyExc_TypeError , msg . c_str ( ) ) ;
return nullptr ;
}
# endif
2016-01-17 21:36:44 +00:00
PyErr_SetString ( PyExc_TypeError , msg . c_str ( ) ) ;
return nullptr ;
}
2021-07-09 13:45:53 +00:00
if ( overloads - > is_constructor & & ! self_value_and_holder . holder_constructed ( ) ) {
auto * pi = reinterpret_cast < instance * > ( parent . ptr ( ) ) ;
self_value_and_holder . type - > init_instance ( pi , nullptr ) ;
}
return result . ptr ( ) ;
2016-01-17 21:36:44 +00:00
}
2015-07-05 18:05:44 +00:00
} ;
2021-07-21 12:22:18 +00:00
2016-01-17 21:36:41 +00:00
/// Wrapper for Python extension modules
2020-09-16 21:15:42 +00:00
class module_ : public object {
2015-07-05 18:05:44 +00:00
public :
2020-09-16 21:15:42 +00:00
PYBIND11_OBJECT_DEFAULT ( module_ , object , PyModule_Check )
2015-07-05 18:05:44 +00:00
2017-01-31 15:54:08 +00:00
/// Create a new top-level Python module with the given name and docstring
2020-10-09 14:46:11 +00:00
PYBIND11_DEPRECATED ( " Use PYBIND11_MODULE or module_::create_extension_module instead " )
explicit module_ ( const char * name , const char * doc = nullptr ) {
2015-09-04 21:42:12 +00:00
# if PY_MAJOR_VERSION >= 3
2020-10-09 14:46:11 +00:00
* this = create_extension_module ( name , doc , new PyModuleDef ( ) ) ;
2015-09-04 21:42:12 +00:00
# else
2020-10-09 14:46:11 +00:00
* this = create_extension_module ( name , doc , nullptr ) ;
2020-10-02 14:01:24 +00:00
# endif
2020-10-09 14:46:11 +00:00
}
2015-07-05 18:05:44 +00:00
2017-01-31 15:54:08 +00:00
/** \rst
Create Python binding for a new function within the module scope . ` ` Func ` `
can be a plain C + + function , a function pointer , or a lambda function . For
details on the ` ` Extra & & . . . extra ` ` argument , see section : ref : ` extras ` .
\ endrst */
2015-07-29 15:43:52 +00:00
template < typename Func , typename . . . Extra >
2020-09-16 21:15:42 +00:00
module_ & def ( const char * name_ , Func & & f , const Extra & . . . extra ) {
2016-09-20 23:06:32 +00:00
cpp_function func ( std : : forward < Func > ( f ) , name ( name_ ) , scope ( * this ) ,
sibling ( getattr ( * this , name_ , none ( ) ) ) , extra . . . ) ;
2016-10-25 01:58:22 +00:00
// NB: allow overwriting here because cpp_function sets up a chain with the intention of
// overwriting (and has already checked internally that it isn't overwriting non-functions).
add_object ( name_ , func , true /* overwrite */ ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2017-01-31 15:54:08 +00:00
/** \rst
Create and return a new Python submodule with the given name and docstring .
This also works recursively , i . e .
. . code - block : : cpp
2020-10-03 17:38:03 +00:00
py : : module_ m ( " example " , " pybind11 example plugin " ) ;
py : : module_ m2 = m . def_submodule ( " sub " , " A submodule of 'example' " ) ;
py : : module_ m3 = m2 . def_submodule ( " subsub " , " A submodule of 'example.sub' " ) ;
2017-01-31 15:54:08 +00:00
\ endrst */
2020-09-16 21:15:42 +00:00
module_ def_submodule ( const char * name , const char * doc = nullptr ) {
2015-07-05 18:05:44 +00:00
std : : string full_name = std : : string ( PyModule_GetName ( m_ptr ) )
+ std : : string ( " . " ) + std : : string ( name ) ;
2020-09-16 21:15:42 +00:00
auto result = reinterpret_borrow < module_ > ( PyImport_AddModule ( full_name . c_str ( ) ) ) ;
2016-11-15 11:38:05 +00:00
if ( doc & & options : : show_user_defined_docstrings ( ) )
2015-10-15 16:13:33 +00:00
result . attr ( " __doc__ " ) = pybind11 : : str ( doc ) ;
2015-07-05 18:05:44 +00:00
attr ( name ) = result ;
return result ;
}
2015-10-13 21:44:25 +00:00
2017-01-31 15:54:08 +00:00
/// Import and return a module or throws `error_already_set`.
2020-09-16 21:15:42 +00:00
static module_ import ( const char * name ) {
2015-12-26 13:04:52 +00:00
PyObject * obj = PyImport_ImportModule ( name ) ;
if ( ! obj )
2016-12-01 10:35:34 +00:00
throw error_already_set ( ) ;
2020-09-16 21:15:42 +00:00
return reinterpret_steal < module_ > ( obj ) ;
2015-10-13 21:44:25 +00:00
}
2016-10-25 01:58:22 +00:00
2017-09-12 06:05:05 +00:00
/// Reload the module or throws `error_already_set`.
void reload ( ) {
PyObject * obj = PyImport_ReloadModule ( ptr ( ) ) ;
if ( ! obj )
throw error_already_set ( ) ;
2020-09-16 21:15:42 +00:00
* this = reinterpret_steal < module_ > ( obj ) ;
2017-09-12 06:05:05 +00:00
}
2020-10-09 14:46:11 +00:00
/** \rst
Adds an object to the module using the given name . Throws if an object with the given name
already exists .
` ` overwrite ` ` should almost always be false : attempting to overwrite objects that pybind11 has
established will , in most cases , break things .
\ endrst */
2017-03-30 09:59:32 +00:00
PYBIND11_NOINLINE void add_object ( const char * name , handle obj , bool overwrite = false ) {
2016-10-25 01:58:22 +00:00
if ( ! overwrite & & hasattr ( * this , name ) )
pybind11_fail ( " Error during initialization: multiple incompatible definitions with name \" " +
std : : string ( name ) + " \" " ) ;
2017-03-30 09:59:32 +00:00
PyModule_AddObject ( ptr ( ) , name , obj . inc_ref ( ) . ptr ( ) /* steals a reference */ ) ;
2016-10-25 01:58:22 +00:00
}
2020-10-02 14:01:24 +00:00
# if PY_MAJOR_VERSION >= 3
2020-10-09 14:46:11 +00:00
using module_def = PyModuleDef ;
# else
struct module_def { } ;
# endif
2020-10-02 14:01:24 +00:00
2020-10-09 14:46:11 +00:00
/** \rst
Create a new top - level module that can be used as the main module of a C extension .
2021-01-14 04:15:58 +00:00
For Python 3 , ` ` def ` ` should point to a statically allocated module_def .
2020-10-09 14:46:11 +00:00
For Python 2 , ` ` def ` ` can be a nullptr and is completely ignored .
\ endrst */
static module_ create_extension_module ( const char * name , const char * doc , module_def * def ) {
# if PY_MAJOR_VERSION >= 3
// module_def is PyModuleDef
2020-10-02 14:01:24 +00:00
def = new ( def ) PyModuleDef { // Placement new (not an allocation).
/* m_base */ PyModuleDef_HEAD_INIT ,
/* m_name */ name ,
/* m_doc */ options : : show_user_defined_docstrings ( ) ? doc : nullptr ,
/* m_size */ - 1 ,
/* m_methods */ nullptr ,
/* m_slots */ nullptr ,
/* m_traverse */ nullptr ,
/* m_clear */ nullptr ,
/* m_free */ nullptr
} ;
2020-10-09 14:46:11 +00:00
auto m = PyModule_Create ( def ) ;
# else
// Ignore module_def *def; only necessary for Python 3
( void ) def ;
auto m = Py_InitModule3 ( name , nullptr , options : : show_user_defined_docstrings ( ) ? doc : nullptr ) ;
2020-10-02 14:01:24 +00:00
# endif
2020-10-09 14:46:11 +00:00
if ( m = = nullptr ) {
if ( PyErr_Occurred ( ) )
throw error_already_set ( ) ;
pybind11_fail ( " Internal error in module_::create_extension_module() " ) ;
}
2021-01-14 04:15:58 +00:00
// TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when returned from PyInit_...
2020-10-09 14:46:11 +00:00
// For Python 2, reinterpret_borrow is correct.
return reinterpret_borrow < module_ > ( m ) ;
}
2015-07-05 18:05:44 +00:00
} ;
2020-10-03 17:38:03 +00:00
// When inside a namespace (or anywhere as long as it's not the first item on a line),
// C++20 allows "module" to be used. This is provided for backward compatibility, and for
// simplicity, if someone wants to use py::module for example, that is perfectly safe.
2020-09-16 21:15:42 +00:00
using module = module_ ;
2017-03-29 22:20:42 +00:00
/// \ingroup python_builtins
2017-06-06 15:05:19 +00:00
/// Return a dictionary representing the global variables in the current execution frame,
/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
inline dict globals ( ) {
PyObject * p = PyEval_GetGlobals ( ) ;
2020-10-03 17:38:03 +00:00
return reinterpret_borrow < dict > ( p ? p : module_ : : import ( " __main__ " ) . attr ( " __dict__ " ) . ptr ( ) ) ;
2017-06-06 15:05:19 +00:00
}
2017-03-29 22:20:42 +00:00
2021-10-19 18:39:29 +00:00
# if PY_VERSION_HEX >= 0x03030000
template < typename . . . Args ,
typename = detail : : enable_if_t < args_are_all_keyword_or_ds < Args . . . > ( ) > >
PYBIND11_DEPRECATED ( " make_simple_namespace should be replaced with py::module_::import( \" types \" ).attr( \" SimpleNamespace \" ) " )
object make_simple_namespace ( Args & & . . . args_ ) {
return module_ : : import ( " types " ) . attr ( " SimpleNamespace " ) ( std : : forward < Args > ( args_ ) . . . ) ;
}
# endif
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
2016-01-17 21:36:44 +00:00
/// Generic support for creating new Python heap types
2016-01-17 21:36:41 +00:00
class generic_type : public object {
2015-07-05 18:05:44 +00:00
public :
2016-01-17 21:36:41 +00:00
PYBIND11_OBJECT_DEFAULT ( generic_type , object , PyType_Check )
2016-01-17 21:36:44 +00:00
protected :
2017-02-15 20:10:25 +00:00
void initialize ( const type_record & rec ) {
2020-10-08 23:09:56 +00:00
if ( rec . scope & & hasattr ( rec . scope , " __dict__ " ) & & rec . scope . attr ( " __dict__ " ) . contains ( rec . name ) )
2017-02-15 20:10:25 +00:00
pybind11_fail ( " generic_type: cannot initialize type \" " + std : : string ( rec . name ) +
" \" : an object with that name is already defined " ) ;
2016-05-31 07:53:28 +00:00
2021-07-27 22:32:26 +00:00
if ( ( rec . module_local ? get_local_type_info ( * rec . type ) : get_global_type_info ( * rec . type ) )
! = nullptr )
2017-02-15 20:10:25 +00:00
pybind11_fail ( " generic_type: type \" " + std : : string ( rec . name ) +
2016-05-31 07:53:28 +00:00
" \" is already registered! " ) ;
2017-02-15 20:10:25 +00:00
m_ptr = make_new_python_type ( rec ) ;
2016-01-17 21:36:41 +00:00
/* Register supplemental type information in C++ dict */
2017-02-15 20:10:25 +00:00
auto * tinfo = new detail : : type_info ( ) ;
tinfo - > type = ( PyTypeObject * ) m_ptr ;
2017-04-21 23:01:30 +00:00
tinfo - > cpptype = rec . type ;
2017-02-15 20:10:25 +00:00
tinfo - > type_size = rec . type_size ;
2018-11-09 19:14:53 +00:00
tinfo - > type_align = rec . type_align ;
2017-03-21 00:15:20 +00:00
tinfo - > operator_new = rec . operator_new ;
2017-02-23 02:36:09 +00:00
tinfo - > holder_size_in_ptrs = size_in_ptrs ( rec . holder_size ) ;
2017-07-25 04:53:23 +00:00
tinfo - > init_instance = rec . init_instance ;
2017-02-15 20:10:25 +00:00
tinfo - > dealloc = rec . dealloc ;
2017-04-21 23:01:30 +00:00
tinfo - > simple_type = true ;
tinfo - > simple_ancestors = true ;
2017-07-29 02:03:44 +00:00
tinfo - > default_holder = rec . default_holder ;
tinfo - > module_local = rec . module_local ;
2017-02-15 20:10:25 +00:00
auto & internals = get_internals ( ) ;
auto tindex = std : : type_index ( * rec . type ) ;
2016-10-23 14:27:13 +00:00
tinfo - > direct_conversions = & internals . direct_conversions [ tindex ] ;
2017-07-29 02:03:44 +00:00
if ( rec . module_local )
2021-07-21 12:22:18 +00:00
get_local_internals ( ) . registered_types_cpp [ tindex ] = tinfo ;
2017-07-29 02:03:44 +00:00
else
internals . registered_types_cpp [ tindex ] = tinfo ;
2017-02-23 02:36:09 +00:00
internals . registered_types_py [ ( PyTypeObject * ) m_ptr ] = { tinfo } ;
2016-12-16 14:00:46 +00:00
2017-04-21 23:01:30 +00:00
if ( rec . bases . size ( ) > 1 | | rec . multiple_inheritance ) {
2017-02-15 20:10:25 +00:00
mark_parents_nonsimple ( tinfo - > type ) ;
2017-04-21 23:01:30 +00:00
tinfo - > simple_ancestors = false ;
}
else if ( rec . bases . size ( ) = = 1 ) {
2022-01-31 17:19:48 +00:00
auto * parent_tinfo = get_type_info ( ( PyTypeObject * ) rec . bases [ 0 ] . ptr ( ) ) ;
assert ( parent_tinfo ! = nullptr ) ;
bool parent_simple_ancestors = parent_tinfo - > simple_ancestors ;
tinfo - > simple_ancestors = parent_simple_ancestors ;
// The parent can no longer be a simple type if it has MI and has a child
parent_tinfo - > simple_type = parent_tinfo - > simple_type & & parent_simple_ancestors ;
2017-04-21 23:01:30 +00:00
}
2017-08-17 15:38:05 +00:00
if ( rec . module_local ) {
// Stash the local typeinfo and loader so that external modules can access it.
tinfo - > module_local_load = & type_caster_generic : : local_load ;
2017-08-20 15:14:09 +00:00
setattr ( m_ptr , PYBIND11_MODULE_LOCAL_ID , capsule ( tinfo ) ) ;
2017-08-17 15:38:05 +00:00
}
2015-07-05 18:05:44 +00:00
}
2016-09-11 11:00:40 +00:00
/// Helper function which tags all parents of a type using mult. inheritance
void mark_parents_nonsimple ( PyTypeObject * value ) {
2016-10-28 01:08:15 +00:00
auto t = reinterpret_borrow < tuple > ( value - > tp_bases ) ;
2016-09-11 11:00:40 +00:00
for ( handle h : t ) {
auto tinfo2 = get_type_info ( ( PyTypeObject * ) h . ptr ( ) ) ;
if ( tinfo2 )
tinfo2 - > simple_type = false ;
mark_parents_nonsimple ( ( PyTypeObject * ) h . ptr ( ) ) ;
}
}
2015-07-28 14:12:20 +00:00
void install_buffer_funcs (
buffer_info * ( * get_buffer ) ( PyObject * , void * ) ,
void * get_buffer_data ) {
2020-09-11 03:20:47 +00:00
auto * type = ( PyHeapTypeObject * ) m_ptr ;
2016-01-17 21:36:41 +00:00
auto tinfo = detail : : get_type_info ( & type - > ht_type ) ;
2016-12-16 14:00:46 +00:00
if ( ! type - > ht_type . tp_as_buffer )
pybind11_fail (
" To be able to register buffer protocol support for the type ' " +
2020-10-02 02:57:25 +00:00
get_fully_qualified_tp_name ( tinfo - > type ) +
2016-12-16 14:00:46 +00:00
" ' the associated class<>(..) invocation must "
" include the pybind11::buffer_protocol() annotation! " ) ;
2016-01-17 21:36:41 +00:00
tinfo - > get_buffer = get_buffer ;
tinfo - > get_buffer_data = get_buffer_data ;
2015-07-05 18:05:44 +00:00
}
2017-11-07 16:35:27 +00:00
// rec_func must be set for either fget or fset.
2016-12-16 14:00:46 +00:00
void def_property_static_impl ( const char * name ,
handle fget , handle fset ,
2017-11-07 16:35:27 +00:00
detail : : function_record * rec_func ) {
2021-07-27 22:32:26 +00:00
const auto is_static = ( rec_func ! = nullptr ) & & ! ( rec_func - > is_method & & rec_func - > scope ) ;
const auto has_doc = ( rec_func ! = nullptr ) & & ( rec_func - > doc ! = nullptr )
& & pybind11 : : options : : show_user_defined_docstrings ( ) ;
2017-02-13 17:11:24 +00:00
auto property = handle ( ( PyObject * ) ( is_static ? get_internals ( ) . static_property_type
: & PyProperty_Type ) ) ;
attr ( name ) = property ( fget . ptr ( ) ? fget : none ( ) ,
fset . ptr ( ) ? fset : none ( ) ,
/*deleter*/ none ( ) ,
2017-11-07 16:35:27 +00:00
pybind11 : : str ( has_doc ? rec_func - > doc : " " ) ) ;
2016-12-16 14:00:46 +00:00
}
2015-07-05 18:05:44 +00:00
} ;
2016-09-06 16:27:00 +00:00
2017-03-21 00:15:20 +00:00
/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
template < typename T , typename = void_t < decltype ( static_cast < void * ( * ) ( size_t ) > ( T : : operator new ) ) > >
void set_operator_new ( type_record * r ) { r - > operator_new = & T : : operator new ; }
template < typename > void set_operator_new ( . . . ) { }
2017-07-23 04:32:58 +00:00
template < typename T , typename SFINAE = void > struct has_operator_delete : std : : false_type { } ;
template < typename T > struct has_operator_delete < T , void_t < decltype ( static_cast < void ( * ) ( void * ) > ( T : : operator delete ) ) > >
: std : : true_type { } ;
template < typename T , typename SFINAE = void > struct has_operator_delete_size : std : : false_type { } ;
template < typename T > struct has_operator_delete_size < T , void_t < decltype ( static_cast < void ( * ) ( void * , size_t ) > ( T : : operator delete ) ) > >
: std : : true_type { } ;
2017-03-21 00:15:20 +00:00
/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
2017-07-23 04:32:58 +00:00
template < typename T , enable_if_t < has_operator_delete < T > : : value , int > = 0 >
2018-11-09 19:14:53 +00:00
void call_operator_delete ( T * p , size_t , size_t ) { T : : operator delete ( p ) ; }
2017-07-23 04:32:58 +00:00
template < typename T , enable_if_t < ! has_operator_delete < T > : : value & & has_operator_delete_size < T > : : value , int > = 0 >
2018-11-09 19:14:53 +00:00
void call_operator_delete ( T * p , size_t s , size_t ) { T : : operator delete ( p , s ) ; }
inline void call_operator_delete ( void * p , size_t s , size_t a ) {
( void ) s ; ( void ) a ;
2019-11-16 00:18:24 +00:00
# if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
2019-06-14 16:12:51 +00:00
if ( a > __STDCPP_DEFAULT_NEW_ALIGNMENT__ ) {
# ifdef __cpp_sized_deallocation
: : operator delete ( p , s , std : : align_val_t ( a ) ) ;
# else
: : operator delete ( p , std : : align_val_t ( a ) ) ;
# endif
return ;
}
# endif
# ifdef __cpp_sized_deallocation
2018-11-09 19:14:53 +00:00
: : operator delete ( p , s ) ;
2019-06-14 16:12:51 +00:00
# else
: : operator delete ( p ) ;
# endif
2018-11-09 19:14:53 +00:00
}
2017-03-21 00:15:20 +00:00
2020-07-26 23:44:25 +00:00
inline void add_class_method ( object & cls , const char * name_ , const cpp_function & cf ) {
cls . attr ( cf . name ( ) ) = cf ;
2022-01-11 22:57:59 +00:00
if ( std : : strcmp ( name_ , " __eq__ " ) = = 0 & & ! cls . attr ( " __dict__ " ) . contains ( " __hash__ " ) ) {
cls . attr ( " __hash__ " ) = none ( ) ;
2020-07-26 23:44:25 +00:00
}
}
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_END ( detail )
2015-07-05 18:05:44 +00:00
2017-05-16 15:07:28 +00:00
/// Given a pointer to a member function, cast it to its `Derived` version.
/// Forward everything else unchanged.
template < typename /*Derived*/ , typename F >
auto method_adaptor ( F & & f ) - > decltype ( std : : forward < F > ( f ) ) { return std : : forward < F > ( f ) ; }
template < typename Derived , typename Return , typename Class , typename . . . Args >
Add informative compilation failure for method_adaptor failures
When using `method_adaptor` (usually implicitly via a `cl.def("f",
&D::f)`) a compilation failure results if `f` is actually a method of
an inaccessible base class made public via `using`, such as:
class B { public: void f() {} };
class D : private B { public: using B::f; };
pybind deduces `&D::f` as a `B` member function pointer. Since the base
class is inaccessible, the cast in `method_adaptor` from a base class
member function pointer to derived class member function pointer isn't
valid, and a cast failure results.
This was sort of a regression in 2.2, which introduced `method_adaptor`
to do the expected thing when the base class *is* accessible. It wasn't
actually something that *worked* in 2.1, though: you wouldn't get a
compile-time failure, but the method was not callable (because the `D *`
couldn't be cast to a `B *` because of the access restriction). As a
result, you'd simply get a run-time failure if you ever tried to call
the function (this is what #855 fixed).
Thus the change in 2.2 essentially promoted a run-time failure to a
compile-time failure, so isn't really a regression.
This commit simply adds a `static_assert` with an accessible-base-class
check so that, rather than just a cryptic cast failure, you get
something more informative (along with a suggestion for a workaround).
The workaround is to use a lambda, e.g.:
class Derived : private Base {
public:
using Base::f;
};
// In binding code:
//cl.def("f", &Derived::f); // fails: &Derived::f is actually a base
// class member function pointer
cl.def("f", [](Derived &self) { return self.f(); });
This is a bit of a nuissance (especially if there are a bunch of
arguments to forward), but I don't really see another solution.
Fixes #1124
2017-10-03 13:09:49 +00:00
auto method_adaptor ( Return ( Class : : * pmf ) ( Args . . . ) ) - > Return ( Derived : : * ) ( Args . . . ) {
static_assert ( detail : : is_accessible_base_of < Class , Derived > : : value ,
" Cannot bind an inaccessible base class method; use a lambda definition instead " ) ;
return pmf ;
}
2017-05-16 15:07:28 +00:00
template < typename Derived , typename Return , typename Class , typename . . . Args >
Add informative compilation failure for method_adaptor failures
When using `method_adaptor` (usually implicitly via a `cl.def("f",
&D::f)`) a compilation failure results if `f` is actually a method of
an inaccessible base class made public via `using`, such as:
class B { public: void f() {} };
class D : private B { public: using B::f; };
pybind deduces `&D::f` as a `B` member function pointer. Since the base
class is inaccessible, the cast in `method_adaptor` from a base class
member function pointer to derived class member function pointer isn't
valid, and a cast failure results.
This was sort of a regression in 2.2, which introduced `method_adaptor`
to do the expected thing when the base class *is* accessible. It wasn't
actually something that *worked* in 2.1, though: you wouldn't get a
compile-time failure, but the method was not callable (because the `D *`
couldn't be cast to a `B *` because of the access restriction). As a
result, you'd simply get a run-time failure if you ever tried to call
the function (this is what #855 fixed).
Thus the change in 2.2 essentially promoted a run-time failure to a
compile-time failure, so isn't really a regression.
This commit simply adds a `static_assert` with an accessible-base-class
check so that, rather than just a cryptic cast failure, you get
something more informative (along with a suggestion for a workaround).
The workaround is to use a lambda, e.g.:
class Derived : private Base {
public:
using Base::f;
};
// In binding code:
//cl.def("f", &Derived::f); // fails: &Derived::f is actually a base
// class member function pointer
cl.def("f", [](Derived &self) { return self.f(); });
This is a bit of a nuissance (especially if there are a bunch of
arguments to forward), but I don't really see another solution.
Fixes #1124
2017-10-03 13:09:49 +00:00
auto method_adaptor ( Return ( Class : : * pmf ) ( Args . . . ) const ) - > Return ( Derived : : * ) ( Args . . . ) const {
static_assert ( detail : : is_accessible_base_of < Class , Derived > : : value ,
" Cannot bind an inaccessible base class method; use a lambda definition instead " ) ;
return pmf ;
}
2017-05-16 15:07:28 +00:00
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
template < typename type_ , typename . . . options >
2016-01-17 21:36:44 +00:00
class class_ : public detail : : generic_type {
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
template < typename T > using is_holder = detail : : is_holder_type < type_ , T > ;
2017-05-16 15:07:28 +00:00
template < typename T > using is_subtype = detail : : is_strict_base_of < type_ , T > ;
template < typename T > using is_base = detail : : is_strict_base_of < T , type_ > ;
Change all_of_t/any_of_t to all_of/any_of, add none_of
This replaces the current `all_of_t<Pred, Ts...>` with `all_of<Ts...>`,
with previous use of `all_of_t<Pred, Ts...>` becoming
`all_of<Pred<Ts>...>` (and similarly for `any_of_t`). It also adds a
`none_of<Ts...>`, a shortcut for `negation<any_of<Ts...>>`.
This allows `all_of` and `any_of` to be used a bit more flexible, e.g.
in cases where several predicates need to be tested for the same type
instead of the same predicate for multiple types.
This commit replaces the implementation with a more efficient version
for non-MSVC. For MSVC, this changes the workaround to use the
built-in, recursive std::conjunction/std::disjunction instead.
This also removes the `count_t` since `any_of_t` and `all_of_t` were the
only things using it.
This commit also rearranges some of the future std imports to use actual
`std` implementations for C++14/17 features when under the appropriate
compiler mode, as we were already doing for a few things (like
index_sequence). Most of these aren't saving much (the implementation
for enable_if_t, for example, is trivial), but I think it makes the
intention of the code instantly clear. It also enables MSVC's native
std::index_sequence support.
2016-12-12 23:11:49 +00:00
// struct instead of using here to help MSVC:
template < typename T > struct is_valid_class_option :
detail : : any_of < is_holder < T > , is_subtype < T > , is_base < T > > { } ;
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
2015-07-05 18:05:44 +00:00
public :
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
using type = type_ ;
2017-03-29 09:55:18 +00:00
using type_alias = detail : : exactly_one_t < is_subtype , void , options . . . > ;
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
constexpr static bool has_alias = ! std : : is_void < type_alias > : : value ;
2017-03-29 09:55:18 +00:00
using holder_type = detail : : exactly_one_t < is_holder , std : : unique_ptr < type > , options . . . > ;
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
Change all_of_t/any_of_t to all_of/any_of, add none_of
This replaces the current `all_of_t<Pred, Ts...>` with `all_of<Ts...>`,
with previous use of `all_of_t<Pred, Ts...>` becoming
`all_of<Pred<Ts>...>` (and similarly for `any_of_t`). It also adds a
`none_of<Ts...>`, a shortcut for `negation<any_of<Ts...>>`.
This allows `all_of` and `any_of` to be used a bit more flexible, e.g.
in cases where several predicates need to be tested for the same type
instead of the same predicate for multiple types.
This commit replaces the implementation with a more efficient version
for non-MSVC. For MSVC, this changes the workaround to use the
built-in, recursive std::conjunction/std::disjunction instead.
This also removes the `count_t` since `any_of_t` and `all_of_t` were the
only things using it.
This commit also rearranges some of the future std imports to use actual
`std` implementations for C++14/17 features when under the appropriate
compiler mode, as we were already doing for a few things (like
index_sequence). Most of these aren't saving much (the implementation
for enable_if_t, for example, is trivial), but I think it makes the
intention of the code instantly clear. It also enables MSVC's native
std::index_sequence support.
2016-12-12 23:11:49 +00:00
static_assert ( detail : : all_of < is_valid_class_option < options > . . . > : : value ,
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
" Unknown/invalid class_ template parameters provided " ) ;
2015-07-05 18:05:44 +00:00
2017-06-13 01:48:36 +00:00
static_assert ( ! has_alias | | std : : is_polymorphic < type > : : value ,
" Cannot use an alias class with a non-polymorphic type " ) ;
2016-10-28 01:08:15 +00:00
PYBIND11_OBJECT ( class_ , generic_type , PyType_Check )
2015-07-05 18:05:44 +00:00
2016-01-17 21:36:44 +00:00
template < typename . . . Extra >
class_ ( handle scope , const char * name , const Extra & . . . extra ) {
2017-03-16 23:10:48 +00:00
using namespace detail ;
// MI can only be specified via class_ template options, not constructor parameters
static_assert (
none_of < is_pyobject < Extra > . . . > : : value | | // no base class arguments, or:
( constexpr_sum ( is_pyobject < Extra > : : value . . . ) = = 1 & & // Exactly one base
constexpr_sum ( is_base < options > : : value . . . ) = = 0 & & // no template option bases
none_of < std : : is_same < multiple_inheritance , Extra > . . . > : : value ) , // no multiple_inheritance attr
" Error: multiple inheritance bases must be specified via class_ template options " ) ;
type_record record ;
2016-01-17 21:36:44 +00:00
record . scope = scope ;
record . name = name ;
record . type = & typeid ( type ) ;
2017-03-16 23:10:48 +00:00
record . type_size = sizeof ( conditional_t < has_alias , type_alias , type > ) ;
2018-11-09 19:14:53 +00:00
record . type_align = alignof ( conditional_t < has_alias , type_alias , type > & ) ;
2017-02-23 02:36:09 +00:00
record . holder_size = sizeof ( holder_type ) ;
2017-07-25 04:53:23 +00:00
record . init_instance = init_instance ;
2016-01-17 21:36:44 +00:00
record . dealloc = dealloc ;
2018-11-11 18:36:55 +00:00
record . default_holder = detail : : is_instantiation < std : : unique_ptr , holder_type > : : value ;
2016-01-17 21:36:44 +00:00
2017-03-21 00:15:20 +00:00
set_operator_new < type > ( & record ) ;
2016-09-11 11:00:40 +00:00
/* Register base classes specified via template arguments to class_, if any */
2017-03-26 01:41:06 +00:00
PYBIND11_EXPAND_SIDE_EFFECTS ( add_base < options > ( record ) ) ;
2016-09-06 16:27:00 +00:00
2016-01-17 21:36:44 +00:00
/* Process optional arguments, if any */
2017-03-16 23:10:48 +00:00
process_attributes < Extra . . . > : : init ( extra . . . , & record ) ;
2016-01-17 21:36:44 +00:00
2017-03-16 23:10:48 +00:00
generic_type : : initialize ( record ) ;
2016-05-26 11:19:27 +00:00
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
if ( has_alias ) {
2021-07-21 12:22:18 +00:00
auto & instances = record . module_local ? get_local_internals ( ) . registered_types_cpp : get_internals ( ) . registered_types_cpp ;
2016-05-26 11:19:27 +00:00
instances [ std : : type_index ( typeid ( type_alias ) ) ] = instances [ std : : type_index ( typeid ( type ) ) ] ;
}
2016-01-17 21:36:44 +00:00
}
2015-07-05 18:05:44 +00:00
2016-09-12 15:36:43 +00:00
template < typename Base , detail : : enable_if_t < is_base < Base > : : value , int > = 0 >
2016-09-11 11:00:40 +00:00
static void add_base ( detail : : type_record & rec ) {
2017-06-21 17:38:10 +00:00
rec . add_base ( typeid ( Base ) , [ ] ( void * src ) - > void * {
2016-09-11 11:00:40 +00:00
return static_cast < Base * > ( reinterpret_cast < type * > ( src ) ) ;
} ) ;
}
2016-09-12 15:36:43 +00:00
template < typename Base , detail : : enable_if_t < ! is_base < Base > : : value , int > = 0 >
2016-09-11 11:00:40 +00:00
static void add_base ( detail : : type_record & ) { }
2015-07-29 15:43:52 +00:00
template < typename Func , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def ( const char * name_ , Func & & f , const Extra & . . . extra ) {
2017-05-16 15:07:28 +00:00
cpp_function cf ( method_adaptor < type > ( std : : forward < Func > ( f ) ) , name ( name_ ) , is_method ( * this ) ,
2016-09-20 23:06:32 +00:00
sibling ( getattr ( * this , name_ , none ( ) ) ) , extra . . . ) ;
2020-07-26 23:44:25 +00:00
add_class_method ( * this , name_ , cf ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < typename Func , typename . . . Extra > class_ &
2017-03-12 20:59:07 +00:00
def_static ( const char * name_ , Func & & f , const Extra & . . . extra ) {
static_assert ( ! std : : is_member_function_pointer < Func > : : value ,
" def_static(...) called with a non-static member function pointer " ) ;
2016-09-20 23:06:32 +00:00
cpp_function cf ( std : : forward < Func > ( f ) , name ( name_ ) , scope ( * this ) ,
sibling ( getattr ( * this , name_ , none ( ) ) ) , extra . . . ) ;
2019-06-11 08:59:57 +00:00
attr ( cf . name ( ) ) = staticmethod ( cf ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < detail : : op_id id , detail : : op_type ot , typename L , typename R , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def ( const detail : : op_ < id , ot , L , R > & op , const Extra & . . . extra ) {
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
op . execute ( * this , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < detail : : op_id id , detail : : op_type ot , typename L , typename R , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def_cast ( const detail : : op_ < id , ot , L , R > & op , const Extra & . . . extra ) {
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
op . execute_cast ( * this , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < typename . . . Args , typename . . . Extra >
2017-08-17 04:01:42 +00:00
class_ & def ( const detail : : initimpl : : constructor < Args . . . > & init , const Extra & . . . extra ) {
2021-07-29 00:01:21 +00:00
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100 ( init ) ;
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
init . execute ( * this , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2016-05-26 11:19:27 +00:00
template < typename . . . Args , typename . . . Extra >
2017-08-17 04:01:42 +00:00
class_ & def ( const detail : : initimpl : : alias_constructor < Args . . . > & init , const Extra & . . . extra ) {
2021-07-29 00:01:21 +00:00
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100 ( init ) ;
Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.
This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options. It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively. (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively). If any unmatched template arguments are provided, a
static assertion fails.
What this means is that you can specify or omit the arguments in any
order:
py::class_<A, PyA> c1(m, "A");
py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");
It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 16:17:06 +00:00
init . execute ( * this , extra . . . ) ;
2016-05-26 11:19:27 +00:00
return * this ;
}
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
template < typename . . . Args , typename . . . Extra >
class_ & def ( detail : : initimpl : : factory < Args . . . > & & init , const Extra & . . . extra ) {
std : : move ( init ) . execute ( * this , extra . . . ) ;
return * this ;
}
2017-08-23 23:53:15 +00:00
template < typename . . . Args , typename . . . Extra >
class_ & def ( detail : : initimpl : : pickle_factory < Args . . . > & & pf , const Extra & . . . extra ) {
std : : move ( pf ) . execute ( * this , extra . . . ) ;
return * this ;
}
2020-11-02 17:39:40 +00:00
template < typename Func >
class_ & def_buffer ( Func & & func ) {
2015-07-28 14:12:20 +00:00
struct capture { Func func ; } ;
2020-09-11 03:20:47 +00:00
auto * ptr = new capture { std : : forward < Func > ( func ) } ;
2015-07-28 14:12:20 +00:00
install_buffer_funcs ( [ ] ( PyObject * obj , void * ptr ) - > buffer_info * {
2017-01-03 10:52:05 +00:00
detail : : make_caster < type > caster ;
2015-07-05 18:05:44 +00:00
if ( ! caster . load ( obj , false ) )
return nullptr ;
2015-07-28 14:12:20 +00:00
return new buffer_info ( ( ( capture * ) ptr ) - > func ( caster ) ) ;
} , ptr ) ;
2020-11-02 17:39:40 +00:00
weakref ( m_ptr , cpp_function ( [ ptr ] ( handle wr ) {
delete ptr ;
wr . dec_ref ( ) ;
} ) ) . release ( ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2017-05-17 08:52:33 +00:00
template < typename Return , typename Class , typename . . . Args >
class_ & def_buffer ( Return ( Class : : * func ) ( Args . . . ) ) {
return def_buffer ( [ func ] ( type & obj ) { return ( obj . * func ) ( ) ; } ) ;
}
template < typename Return , typename Class , typename . . . Args >
class_ & def_buffer ( Return ( Class : : * func ) ( Args . . . ) const ) {
return def_buffer ( [ func ] ( const type & obj ) { return ( obj . * func ) ( ) ; } ) ;
}
2015-07-29 15:43:52 +00:00
template < typename C , typename D , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def_readwrite ( const char * name , D C : : * pm , const Extra & . . . extra ) {
2019-06-11 20:25:12 +00:00
static_assert ( std : : is_same < C , type > : : value | | std : : is_base_of < C , type > : : value , " def_readwrite() requires a class member (or base class member) " ) ;
2017-05-16 15:07:28 +00:00
cpp_function fget ( [ pm ] ( const type & c ) - > const D & { return c . * pm ; } , is_method ( * this ) ) ,
fset ( [ pm ] ( type & c , const D & value ) { c . * pm = value ; } , is_method ( * this ) ) ;
2016-03-25 15:13:10 +00:00
def_property ( name , fget , fset , return_value_policy : : reference_internal , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < typename C , typename D , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def_readonly ( const char * name , const D C : : * pm , const Extra & . . . extra ) {
2019-06-11 20:25:12 +00:00
static_assert ( std : : is_same < C , type > : : value | | std : : is_base_of < C , type > : : value , " def_readonly() requires a class member (or base class member) " ) ;
2017-05-16 15:07:28 +00:00
cpp_function fget ( [ pm ] ( const type & c ) - > const D & { return c . * pm ; } , is_method ( * this ) ) ;
2016-03-25 15:13:10 +00:00
def_property_readonly ( name , fget , return_value_policy : : reference_internal , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < typename D , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def_readwrite_static ( const char * name , D * pm , const Extra & . . . extra ) {
2021-06-19 17:53:27 +00:00
cpp_function fget ( [ pm ] ( const object & ) - > const D & { return * pm ; } , scope ( * this ) ) ,
fset ( [ pm ] ( const object & , const D & value ) { * pm = value ; } , scope ( * this ) ) ;
2016-03-25 15:13:10 +00:00
def_property_static ( name , fget , fset , return_value_policy : : reference , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-07-29 15:43:52 +00:00
template < typename D , typename . . . Extra >
2016-01-17 21:36:44 +00:00
class_ & def_readonly_static ( const char * name , const D * pm , const Extra & . . . extra ) {
2021-06-19 17:53:27 +00:00
cpp_function fget ( [ pm ] ( const object & ) - > const D & { return * pm ; } , scope ( * this ) ) ;
2016-03-25 15:13:10 +00:00
def_property_readonly_static ( name , fget , return_value_policy : : reference , extra . . . ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2016-11-01 10:44:57 +00:00
/// Uses return_value_policy::reference_internal by default
template < typename Getter , typename . . . Extra >
class_ & def_property_readonly ( const char * name , const Getter & fget , const Extra & . . . extra ) {
2017-05-16 15:07:28 +00:00
return def_property_readonly ( name , cpp_function ( method_adaptor < type > ( fget ) ) ,
return_value_policy : : reference_internal , extra . . . ) ;
2016-11-01 10:44:57 +00:00
}
/// Uses cpp_function's return_value_policy by default
2016-03-21 16:54:24 +00:00
template < typename . . . Extra >
class_ & def_property_readonly ( const char * name , const cpp_function & fget , const Extra & . . . extra ) {
2017-11-07 16:35:27 +00:00
return def_property ( name , fget , nullptr , extra . . . ) ;
2016-11-01 10:44:57 +00:00
}
/// Uses return_value_policy::reference by default
template < typename Getter , typename . . . Extra >
class_ & def_property_readonly_static ( const char * name , const Getter & fget , const Extra & . . . extra ) {
return def_property_readonly_static ( name , cpp_function ( fget ) , return_value_policy : : reference , extra . . . ) ;
2015-07-05 18:05:44 +00:00
}
2016-11-01 10:44:57 +00:00
/// Uses cpp_function's return_value_policy by default
2016-03-21 16:54:24 +00:00
template < typename . . . Extra >
class_ & def_property_readonly_static ( const char * name , const cpp_function & fget , const Extra & . . . extra ) {
2017-11-07 16:35:27 +00:00
return def_property_static ( name , fget , nullptr , extra . . . ) ;
2016-11-01 10:44:57 +00:00
}
/// Uses return_value_policy::reference_internal by default
2017-05-16 15:07:28 +00:00
template < typename Getter , typename Setter , typename . . . Extra >
class_ & def_property ( const char * name , const Getter & fget , const Setter & fset , const Extra & . . . extra ) {
return def_property ( name , fget , cpp_function ( method_adaptor < type > ( fset ) ) , extra . . . ) ;
}
2016-11-01 10:44:57 +00:00
template < typename Getter , typename . . . Extra >
class_ & def_property ( const char * name , const Getter & fget , const cpp_function & fset , const Extra & . . . extra ) {
2017-05-16 15:07:28 +00:00
return def_property ( name , cpp_function ( method_adaptor < type > ( fget ) ) , fset ,
return_value_policy : : reference_internal , extra . . . ) ;
2015-07-05 18:05:44 +00:00
}
2016-11-01 10:44:57 +00:00
/// Uses cpp_function's return_value_policy by default
2016-03-21 16:54:24 +00:00
template < typename . . . Extra >
class_ & def_property ( const char * name , const cpp_function & fget , const cpp_function & fset , const Extra & . . . extra ) {
2016-03-25 15:13:10 +00:00
return def_property_static ( name , fget , fset , is_method ( * this ) , extra . . . ) ;
2015-07-05 18:05:44 +00:00
}
2016-11-01 10:44:57 +00:00
/// Uses return_value_policy::reference by default
template < typename Getter , typename . . . Extra >
class_ & def_property_static ( const char * name , const Getter & fget , const cpp_function & fset , const Extra & . . . extra ) {
return def_property_static ( name , cpp_function ( fget ) , fset , return_value_policy : : reference , extra . . . ) ;
}
/// Uses cpp_function's return_value_policy by default
2016-03-21 16:54:24 +00:00
template < typename . . . Extra >
class_ & def_property_static ( const char * name , const cpp_function & fget , const cpp_function & fset , const Extra & . . . extra ) {
2019-06-11 12:25:35 +00:00
static_assert ( 0 = = detail : : constexpr_sum ( std : : is_base_of < arg , Extra > : : value . . . ) ,
" Argument annotations are not allowed for properties " ) ;
2016-03-21 16:54:24 +00:00
auto rec_fget = get_function_record ( fget ) , rec_fset = get_function_record ( fset ) ;
2017-11-07 16:35:27 +00:00
auto * rec_active = rec_fget ;
if ( rec_fget ) {
char * doc_prev = rec_fget - > doc ; /* 'extra' field may include a property-specific documentation string */
detail : : process_attributes < Extra . . . > : : init ( extra . . . , rec_fget ) ;
if ( rec_fget - > doc & & rec_fget - > doc ! = doc_prev ) {
2021-10-04 00:15:37 +00:00
std : : free ( doc_prev ) ;
2021-07-26 18:28:36 +00:00
rec_fget - > doc = PYBIND11_COMPAT_STRDUP ( rec_fget - > doc ) ;
2017-11-07 16:35:27 +00:00
}
2016-06-02 18:33:01 +00:00
}
if ( rec_fset ) {
2017-11-07 16:35:27 +00:00
char * doc_prev = rec_fset - > doc ;
2016-03-21 16:54:24 +00:00
detail : : process_attributes < Extra . . . > : : init ( extra . . . , rec_fset ) ;
2016-06-02 18:33:01 +00:00
if ( rec_fset - > doc & & rec_fset - > doc ! = doc_prev ) {
2021-10-04 00:15:37 +00:00
std : : free ( doc_prev ) ;
2021-07-26 18:28:36 +00:00
rec_fset - > doc = PYBIND11_COMPAT_STRDUP ( rec_fset - > doc ) ;
2016-06-02 18:33:01 +00:00
}
2017-11-07 16:35:27 +00:00
if ( ! rec_active ) rec_active = rec_fset ;
2016-06-02 18:33:01 +00:00
}
2017-11-07 16:35:27 +00:00
def_property_static_impl ( name , fget , fset , rec_active ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2015-10-01 14:46:03 +00:00
2015-07-05 18:05:44 +00:00
private :
2016-01-17 21:36:40 +00:00
/// Initialize holder object, variant 1: object derives from enable_shared_from_this
template < typename T >
2017-07-25 04:53:23 +00:00
static void init_holder ( detail : : instance * inst , detail : : value_and_holder & v_h ,
2017-02-23 02:36:09 +00:00
const holder_type * /* unused */ , const std : : enable_shared_from_this < T > * /* dummy */ ) {
2021-01-30 19:05:13 +00:00
auto sh = std : : dynamic_pointer_cast < typename holder_type : : element_type > (
detail : : try_get_shared_from_this ( v_h . value_ptr < type > ( ) ) ) ;
if ( sh ) {
new ( std : : addressof ( v_h . holder < holder_type > ( ) ) ) holder_type ( std : : move ( sh ) ) ;
v_h . set_holder_constructed ( ) ;
}
2017-02-23 02:36:09 +00:00
if ( ! v_h . holder_constructed ( ) & & inst - > owned ) {
2018-06-20 15:33:50 +00:00
new ( std : : addressof ( v_h . holder < holder_type > ( ) ) ) holder_type ( v_h . value_ptr < type > ( ) ) ;
2017-02-23 02:36:09 +00:00
v_h . set_holder_constructed ( ) ;
2015-11-24 22:05:58 +00:00
}
2016-01-17 21:36:40 +00:00
}
2017-02-23 02:36:09 +00:00
static void init_holder_from_existing ( const detail : : value_and_holder & v_h ,
const holder_type * holder_ptr , std : : true_type /*is_copy_constructible*/ ) {
2018-06-20 15:33:50 +00:00
new ( std : : addressof ( v_h . holder < holder_type > ( ) ) ) holder_type ( * reinterpret_cast < const holder_type * > ( holder_ptr ) ) ;
2017-01-31 16:05:44 +00:00
}
2017-02-23 02:36:09 +00:00
static void init_holder_from_existing ( const detail : : value_and_holder & v_h ,
const holder_type * holder_ptr , std : : false_type /*is_copy_constructible*/ ) {
2018-06-20 15:33:50 +00:00
new ( std : : addressof ( v_h . holder < holder_type > ( ) ) ) holder_type ( std : : move ( * const_cast < holder_type * > ( holder_ptr ) ) ) ;
2017-01-31 16:05:44 +00:00
}
2016-01-17 21:36:40 +00:00
/// Initialize holder object, variant 2: try to construct from existing holder object, if possible
2017-07-25 04:53:23 +00:00
static void init_holder ( detail : : instance * inst , detail : : value_and_holder & v_h ,
2017-02-23 02:36:09 +00:00
const holder_type * holder_ptr , const void * /* dummy -- not enable_shared_from_this<T>) */ ) {
2016-12-07 01:36:44 +00:00
if ( holder_ptr ) {
2017-02-23 02:36:09 +00:00
init_holder_from_existing ( v_h , holder_ptr , std : : is_copy_constructible < holder_type > ( ) ) ;
v_h . set_holder_constructed ( ) ;
2016-12-15 22:44:23 +00:00
} else if ( inst - > owned | | detail : : always_construct_holder < holder_type > : : value ) {
2018-06-20 15:33:50 +00:00
new ( std : : addressof ( v_h . holder < holder_type > ( ) ) ) holder_type ( v_h . value_ptr < type > ( ) ) ;
2017-02-23 02:36:09 +00:00
v_h . set_holder_constructed ( ) ;
2016-12-07 01:36:44 +00:00
}
2016-01-17 21:36:40 +00:00
}
2017-07-25 04:53:23 +00:00
/// Performs instance initialization including constructing a holder and registering the known
/// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
/// optional pointer to an existing holder to use; if not specified and the instance is
/// `.owned`, a new holder will be constructed to manage the value pointer.
static void init_instance ( detail : : instance * inst , const void * holder_ptr ) {
2017-02-23 02:36:09 +00:00
auto v_h = inst - > get_value_and_holder ( detail : : get_type_info ( typeid ( type ) ) ) ;
2017-07-29 07:56:01 +00:00
if ( ! v_h . instance_registered ( ) ) {
register_instance ( inst , v_h . value_ptr ( ) , v_h . type ) ;
v_h . set_instance_registered ( ) ;
}
2017-07-25 04:53:23 +00:00
init_holder ( inst , v_h , ( const holder_type * ) holder_ptr , v_h . value_ptr < type > ( ) ) ;
2015-11-24 22:05:58 +00:00
}
2017-02-23 02:36:09 +00:00
/// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
static void dealloc ( detail : : value_and_holder & v_h ) {
2020-08-01 00:46:12 +00:00
// We could be deallocating because we are cleaning up after a Python exception.
// If so, the Python error indicator will be set. We need to clear that before
// running the destructor, in case the destructor code calls more Python.
// If we don't, the Python API will exit with an exception, and pybind11 will
// throw error_already_set from the C++ destructor which is forbidden and triggers
// std::terminate().
error_scope scope ;
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
if ( v_h . holder_constructed ( ) ) {
2017-02-23 02:36:09 +00:00
v_h . holder < holder_type > ( ) . ~ holder_type ( ) ;
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
v_h . set_holder_constructed ( false ) ;
}
else {
2018-11-09 19:14:53 +00:00
detail : : call_operator_delete ( v_h . value_ptr < type > ( ) ,
v_h . type - > type_size ,
v_h . type - > type_align
) ;
Allow binding factory functions as constructors
This allows you to use:
cls.def(py::init(&factory_function));
where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type). Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.
Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
`py::init<...>()`, but keeps the naming consistent: the existing
templated, no-argument one wraps constructors, the no-template,
function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
is required (i.e. python-side inheritance and a declared alias), a
dynamic_cast to the alias is attempted (for the pointer version); if
it fails, or if returned by value, an Alias(Class &&) constructor
is invoked. If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
the wrapped pointer to the alias to see if it is already an alias
instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
two factories: the first is called when an alias is not needed, the
second when it is.
- Reimplement factory instance clearing. The previous implementation
failed under python-side multiple inheritance: *each* inherited
type's factory init would clear the instance instead of only setting
its own type value. The new implementation here clears just the
relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
nullptr and the `holder_constructed` flag to false so that it can be
used to clear preallocated value without needing to rebuild the
instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
completely avoid the extra overhead of needing an extra
allocation/deallocation.
- Updated documentation to make factory constructors the default
advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
throw away the first instance, replacing it with the second; or we can
ignore the second call. The latter is slightly easier, so do that.
2017-06-13 01:52:48 +00:00
}
v_h . value_ptr ( ) = nullptr ;
2015-07-05 18:05:44 +00:00
}
2016-03-21 16:54:24 +00:00
static detail : : function_record * get_function_record ( handle h ) {
h = detail : : get_function ( h ) ;
2016-12-16 14:00:46 +00:00
return h ? ( detail : : function_record * ) reinterpret_borrow < capsule > ( PyCFunction_GET_SELF ( h . ptr ( ) ) )
2016-10-28 01:08:15 +00:00
: nullptr ;
2016-03-21 16:54:24 +00:00
}
2015-07-05 18:05:44 +00:00
} ;
2017-08-30 21:40:55 +00:00
/// Binds an existing constructor taking arguments Args...
template < typename . . . Args > detail : : initimpl : : constructor < Args . . . > init ( ) { return { } ; }
/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
/// when not inheriting on the Python side).
template < typename . . . Args > detail : : initimpl : : alias_constructor < Args . . . > init_alias ( ) { return { } ; }
/// Binds a factory function as a constructor
template < typename Func , typename Ret = detail : : initimpl : : factory < Func > >
Ret init ( Func & & f ) { return { std : : forward < Func > ( f ) } ; }
/// Dual-argument factory function: the first function is called when no alias is needed, the second
/// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
template < typename CFunc , typename AFunc , typename Ret = detail : : initimpl : : factory < CFunc , AFunc > >
Ret init ( CFunc & & c , AFunc & & a ) {
return { std : : forward < CFunc > ( c ) , std : : forward < AFunc > ( a ) } ;
}
/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
template < typename GetState , typename SetState >
detail : : initimpl : : pickle_factory < GetState , SetState > pickle ( GetState & & g , SetState & & s ) {
return { std : : forward < GetState > ( g ) , std : : forward < SetState > ( s ) } ;
2017-09-04 17:37:16 +00:00
}
2017-08-30 21:40:55 +00:00
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
2020-09-19 23:12:19 +00:00
inline str enum_name ( handle arg ) {
dict entries = arg . get_type ( ) . attr ( " __entries " ) ;
2020-09-22 21:36:25 +00:00
for ( auto kv : entries ) {
2020-09-19 23:12:19 +00:00
if ( handle ( kv . second [ int_ ( 0 ) ] ) . equal ( arg ) )
return pybind11 : : str ( kv . first ) ;
}
return " ??? " ;
}
2018-08-31 23:20:24 +00:00
struct enum_base {
2021-08-23 22:42:19 +00:00
enum_base ( const handle & base , const handle & parent ) : m_base ( base ) , m_parent ( parent ) { }
2018-08-31 23:20:24 +00:00
PYBIND11_NOINLINE void init ( bool is_arithmetic , bool is_convertible ) {
m_base . attr ( " __entries " ) = dict ( ) ;
auto property = handle ( ( PyObject * ) & PyProperty_Type ) ;
auto static_property = handle ( ( PyObject * ) get_internals ( ) . static_property_type ) ;
m_base . attr ( " __repr__ " ) = cpp_function (
2021-06-22 16:11:54 +00:00
[ ] ( const object & arg ) - > str {
2020-09-16 15:32:17 +00:00
handle type = type : : handle_of ( arg ) ;
2018-08-31 23:20:24 +00:00
object type_name = type . attr ( " __name__ " ) ;
2020-09-19 23:12:19 +00:00
return pybind11 : : str ( " <{}.{}: {}> " ) . format ( type_name , enum_name ( arg ) , int_ ( arg ) ) ;
2021-06-22 16:11:54 +00:00
} ,
name ( " __repr__ " ) ,
is_method ( m_base ) ) ;
2018-08-31 23:20:24 +00:00
2020-09-19 23:12:19 +00:00
m_base . attr ( " name " ) = property ( cpp_function ( & enum_name , name ( " name " ) , is_method ( m_base ) ) ) ;
m_base . attr ( " __str__ " ) = cpp_function (
2018-08-31 23:20:24 +00:00
[ ] ( handle arg ) - > str {
2020-09-19 23:12:19 +00:00
object type_name = type : : handle_of ( arg ) . attr ( " __name__ " ) ;
return pybind11 : : str ( " {}.{} " ) . format ( type_name , enum_name ( arg ) ) ;
2020-01-25 22:38:01 +00:00
} , name ( " name " ) , is_method ( m_base )
2020-09-19 23:12:19 +00:00
) ;
2018-08-31 23:20:24 +00:00
m_base . attr ( " __doc__ " ) = static_property ( cpp_function (
[ ] ( handle arg ) - > std : : string {
std : : string docstring ;
dict entries = arg . attr ( " __entries " ) ;
if ( ( ( PyTypeObject * ) arg . ptr ( ) ) - > tp_doc )
docstring + = std : : string ( ( ( PyTypeObject * ) arg . ptr ( ) ) - > tp_doc ) + " \n \n " ;
docstring + = " Members: " ;
2020-09-19 18:23:47 +00:00
for ( auto kv : entries ) {
2018-08-31 23:20:24 +00:00
auto key = std : : string ( pybind11 : : str ( kv . first ) ) ;
auto comment = kv . second [ int_ ( 1 ) ] ;
docstring + = " \n \n " + key ;
if ( ! comment . is_none ( ) )
docstring + = " : " + ( std : : string ) pybind11 : : str ( comment ) ;
}
return docstring ;
2020-01-25 22:38:01 +00:00
} , name ( " __doc__ " )
2018-08-31 23:20:24 +00:00
) , none ( ) , none ( ) , " " ) ;
m_base . attr ( " __members__ " ) = static_property ( cpp_function (
[ ] ( handle arg ) - > dict {
dict entries = arg . attr ( " __entries " ) , m ;
2020-09-19 18:23:47 +00:00
for ( auto kv : entries )
2018-08-31 23:20:24 +00:00
m [ kv . first ] = kv . second [ int_ ( 0 ) ] ;
return m ;
2020-01-25 22:38:01 +00:00
} , name ( " __members__ " ) ) , none ( ) , none ( ) , " "
2018-08-31 23:20:24 +00:00
) ;
2021-06-19 17:53:27 +00:00
# define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
m_base . attr ( op ) = cpp_function ( \
[ ] ( const object & a , const object & b ) { \
if ( ! type : : handle_of ( a ) . is ( type : : handle_of ( b ) ) ) \
2021-08-06 18:30:28 +00:00
strict_behavior ; /* NOLINT(bugprone-macro-parentheses) */ \
2021-06-19 17:53:27 +00:00
return expr ; \
} , \
name ( op ) , \
is_method ( m_base ) , \
arg ( " other " ) )
# define PYBIND11_ENUM_OP_CONV(op, expr) \
m_base . attr ( op ) = cpp_function ( \
[ ] ( const object & a_ , const object & b_ ) { \
int_ a ( a_ ) , b ( b_ ) ; \
return expr ; \
} , \
name ( op ) , \
is_method ( m_base ) , \
arg ( " other " ) )
# define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
m_base . attr ( op ) = cpp_function ( \
[ ] ( const object & a_ , const object & b ) { \
int_ a ( a_ ) ; \
return expr ; \
} , \
name ( op ) , \
is_method ( m_base ) , \
arg ( " other " ) )
2019-09-19 16:23:27 +00:00
2018-08-31 23:20:24 +00:00
if ( is_convertible ) {
2019-09-19 16:23:27 +00:00
PYBIND11_ENUM_OP_CONV_LHS ( " __eq__ " , ! b . is_none ( ) & & a . equal ( b ) ) ;
PYBIND11_ENUM_OP_CONV_LHS ( " __ne__ " , b . is_none ( ) | | ! a . equal ( b ) ) ;
2018-08-31 23:20:24 +00:00
if ( is_arithmetic ) {
PYBIND11_ENUM_OP_CONV ( " __lt__ " , a < b ) ;
PYBIND11_ENUM_OP_CONV ( " __gt__ " , a > b ) ;
PYBIND11_ENUM_OP_CONV ( " __le__ " , a < = b ) ;
PYBIND11_ENUM_OP_CONV ( " __ge__ " , a > = b ) ;
PYBIND11_ENUM_OP_CONV ( " __and__ " , a & b ) ;
PYBIND11_ENUM_OP_CONV ( " __rand__ " , a & b ) ;
PYBIND11_ENUM_OP_CONV ( " __or__ " , a | b ) ;
PYBIND11_ENUM_OP_CONV ( " __ror__ " , a | b ) ;
PYBIND11_ENUM_OP_CONV ( " __xor__ " , a ^ b ) ;
PYBIND11_ENUM_OP_CONV ( " __rxor__ " , a ^ b ) ;
2021-06-22 16:11:54 +00:00
m_base . attr ( " __invert__ " )
= cpp_function ( [ ] ( const object & arg ) { return ~ ( int_ ( arg ) ) ; } ,
name ( " __invert__ " ) ,
is_method ( m_base ) ) ;
2018-08-31 23:20:24 +00:00
}
} else {
2018-10-24 09:18:58 +00:00
PYBIND11_ENUM_OP_STRICT ( " __eq__ " , int_ ( a ) . equal ( int_ ( b ) ) , return false ) ;
PYBIND11_ENUM_OP_STRICT ( " __ne__ " , ! int_ ( a ) . equal ( int_ ( b ) ) , return true ) ;
2018-08-31 23:20:24 +00:00
if ( is_arithmetic ) {
2018-11-03 12:20:08 +00:00
# define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
PYBIND11_ENUM_OP_STRICT ( " __lt__ " , int_ ( a ) < int_ ( b ) , PYBIND11_THROW ) ;
PYBIND11_ENUM_OP_STRICT ( " __gt__ " , int_ ( a ) > int_ ( b ) , PYBIND11_THROW ) ;
PYBIND11_ENUM_OP_STRICT ( " __le__ " , int_ ( a ) < = int_ ( b ) , PYBIND11_THROW ) ;
PYBIND11_ENUM_OP_STRICT ( " __ge__ " , int_ ( a ) > = int_ ( b ) , PYBIND11_THROW ) ;
# undef PYBIND11_THROW
2018-08-31 23:20:24 +00:00
}
}
2019-09-19 16:23:27 +00:00
# undef PYBIND11_ENUM_OP_CONV_LHS
2018-08-31 23:20:24 +00:00
# undef PYBIND11_ENUM_OP_CONV
# undef PYBIND11_ENUM_OP_STRICT
2020-01-25 22:38:01 +00:00
m_base . attr ( " __getstate__ " ) = cpp_function (
2021-06-22 16:11:54 +00:00
[ ] ( const object & arg ) { return int_ ( arg ) ; } , name ( " __getstate__ " ) , is_method ( m_base ) ) ;
2018-08-31 23:20:24 +00:00
2020-01-25 22:38:01 +00:00
m_base . attr ( " __hash__ " ) = cpp_function (
2021-06-22 16:11:54 +00:00
[ ] ( const object & arg ) { return int_ ( arg ) ; } , name ( " __hash__ " ) , is_method ( m_base ) ) ;
2018-08-31 23:20:24 +00:00
}
PYBIND11_NOINLINE void value ( char const * name_ , object value , const char * doc = nullptr ) {
dict entries = m_base . attr ( " __entries " ) ;
str name ( name_ ) ;
if ( entries . contains ( name ) ) {
std : : string type_name = ( std : : string ) str ( m_base . attr ( " __name__ " ) ) ;
throw value_error ( type_name + " : element \" " + std : : string ( name_ ) + " \" already exists! " ) ;
}
entries [ name ] = std : : make_pair ( value , doc ) ;
m_base . attr ( name ) = value ;
}
PYBIND11_NOINLINE void export_values ( ) {
dict entries = m_base . attr ( " __entries " ) ;
2020-09-19 18:23:47 +00:00
for ( auto kv : entries )
2018-08-31 23:20:24 +00:00
m_parent . attr ( kv . first ) = kv . second [ int_ ( 0 ) ] ;
}
handle m_base ;
handle m_parent ;
} ;
2021-08-26 21:34:24 +00:00
template < bool is_signed , size_t length > struct equivalent_integer { } ;
template < > struct equivalent_integer < true , 1 > { using type = int8_t ; } ;
template < > struct equivalent_integer < false , 1 > { using type = uint8_t ; } ;
template < > struct equivalent_integer < true , 2 > { using type = int16_t ; } ;
template < > struct equivalent_integer < false , 2 > { using type = uint16_t ; } ;
template < > struct equivalent_integer < true , 4 > { using type = int32_t ; } ;
template < > struct equivalent_integer < false , 4 > { using type = uint32_t ; } ;
template < > struct equivalent_integer < true , 8 > { using type = int64_t ; } ;
template < > struct equivalent_integer < false , 8 > { using type = uint64_t ; } ;
template < typename IntLike >
using equivalent_integer_t = typename equivalent_integer < std : : is_signed < IntLike > : : value , sizeof ( IntLike ) > : : type ;
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_END ( detail )
2018-08-31 23:20:24 +00:00
2015-07-05 18:05:44 +00:00
/// Binds C++ enumerations and enumeration classes to Python
template < typename Type > class enum_ : public class_ < Type > {
public :
2018-09-14 10:07:47 +00:00
using Base = class_ < Type > ;
using Base : : def ;
using Base : : attr ;
using Base : : def_property_readonly ;
using Base : : def_property_readonly_static ;
2021-08-26 21:34:24 +00:00
using Underlying = typename std : : underlying_type < Type > : : type ;
// Scalar is the integer representation of underlying type
using Scalar = detail : : conditional_t < detail : : any_of <
detail : : is_std_char_type < Underlying > , std : : is_same < Underlying , bool >
> : : value , detail : : equivalent_integer_t < Underlying > , Underlying > ;
2016-11-17 22:24:47 +00:00
2016-01-17 21:36:44 +00:00
template < typename . . . Extra >
enum_ ( const handle & scope , const char * name , const Extra & . . . extra )
2018-08-31 23:20:24 +00:00
: class_ < Type > ( scope , name , extra . . . ) , m_base ( * this , scope ) {
2017-03-29 09:55:18 +00:00
constexpr bool is_arithmetic = detail : : any_of < std : : is_same < arithmetic , Extra > . . . > : : value ;
2021-08-26 21:34:24 +00:00
constexpr bool is_convertible = std : : is_convertible < Type , Underlying > : : value ;
2018-08-31 23:20:24 +00:00
m_base . init ( is_arithmetic , is_convertible ) ;
2016-11-17 22:24:47 +00:00
2020-11-10 17:49:42 +00:00
def ( init ( [ ] ( Scalar i ) { return static_cast < Type > ( i ) ; } ) , arg ( " value " ) ) ;
2020-12-31 16:08:15 +00:00
def_property_readonly ( " value " , [ ] ( Type value ) { return ( Scalar ) value ; } ) ;
2016-11-17 22:24:47 +00:00
def ( " __int__ " , [ ] ( Type value ) { return ( Scalar ) value ; } ) ;
2017-04-28 12:46:52 +00:00
# if PY_MAJOR_VERSION < 3
def ( " __long__ " , [ ] ( Type value ) { return ( Scalar ) value ; } ) ;
# endif
2019-09-21 16:09:35 +00:00
# if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
2019-09-20 09:06:10 +00:00
def ( " __index__ " , [ ] ( Type value ) { return ( Scalar ) value ; } ) ;
# endif
2020-01-25 22:38:01 +00:00
attr ( " __setstate__ " ) = cpp_function (
[ ] ( detail : : value_and_holder & v_h , Scalar arg ) {
detail : : initimpl : : setstate < Base > ( v_h , static_cast < Type > ( arg ) ,
Py_TYPE ( v_h . inst ) ! = v_h . type - > type ) ; } ,
detail : : is_new_style_constructor ( ) ,
2020-11-10 17:49:42 +00:00
pybind11 : : name ( " __setstate__ " ) , is_method ( * this ) , arg ( " state " ) ) ;
2015-07-05 18:05:44 +00:00
}
/// Export enumeration entries into the parent scope
2017-03-03 16:45:50 +00:00
enum_ & export_values ( ) {
2018-08-31 23:20:24 +00:00
m_base . export_values ( ) ;
2016-11-04 15:51:14 +00:00
return * this ;
2015-07-05 18:05:44 +00:00
}
/// Add an enumeration entry
2017-11-16 21:24:36 +00:00
enum_ & value ( char const * name , Type value , const char * doc = nullptr ) {
2018-08-31 23:20:24 +00:00
m_base . value ( name , pybind11 : : cast ( value , return_value_policy : : copy ) , doc ) ;
2015-07-05 18:05:44 +00:00
return * this ;
}
2017-03-03 16:45:50 +00:00
2015-07-05 18:05:44 +00:00
private :
2018-08-31 23:20:24 +00:00
detail : : enum_base m_base ;
2015-07-05 18:05:44 +00:00
} ;
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
2016-01-17 21:36:39 +00:00
Implement py::init_alias<>() constructors
This commit adds support for forcing alias type initialization by
defining constructors with `py::init_alias<arg1, arg2>()` instead of
`py::init<arg1, arg2>()`. Currently py::init<> only results in Alias
initialization if the type is extended in python, or the given
arguments can't be used to construct the base type, but can be used to
construct the alias. py::init_alias<>, in contrast, always invokes the
constructor of the alias type.
It looks like this was already the intention of
`py::detail::init_alias`, which was forward-declared in
86d825f3302701d81414ddd3d38bcd09433076bc, but was apparently never
finished: despite the existance of a .def method accepting it, the
`detail::init_alias` class isn't actually defined anywhere.
This commit completes the feature (or possibly repurposes it), allowing
declaration of classes that will always initialize the trampoline which
is (as I argued in #397) sometimes useful.
2016-09-09 06:42:51 +00:00
PYBIND11_NOINLINE-related cleanup. (#3179)
* Removing pragma for GCC -Wattributes, fixing forward declarations.
* Introducing PYBIND11_NOINLINE_FWD to deal with CUDA, GCC7, GCC8.
* Updating PYBIND11_NOINLINE_DCL in Doxyfile.
* Trying noinline, noinline for {CUDA, GCC7, GCC8}
* Trying noinline, inline for {CUDA, GCC7, GCC8}
* Adding GCC -Wattributes `pragma` in 3 header files.
* Introducing PYBIND11_NOINLINE_GCC_PRAGMA_ATTRIBUTES_NEEDED, used in 9 header files.
* Removing ICC pragma 2196, to see if it is still needed.
* Trying noinline, noinline for ICC
* Trying noinline, inline for ICC
* Restoring ICC pragma 2196, introducing PYBIND11_NOINLINE_FORCED, defined for testing.
* Removing code accidentally left in (was for experimentation only).
* Removing one-time-test define.
* Removing PYBIND11_NOINLINE_FWD macro (after learning that it makes no sense).
* Testing with PYBIND11_NOINLINE_DISABLED. Minor non-functional enhancements.
* Removing #define PYBIND11_NOINLINE_DISABLED (test was successful).
* Removing PYBIND11_NOINLINE_FORCED and enhancing comments for PYBIND11_NOINLINE.
* WIP stripping back
* Making -Wattributes pragma in pybind11 specific to GCC7, GCC8, CUDA.
2021-08-09 17:10:38 +00:00
PYBIND11_NOINLINE void keep_alive_impl ( handle nurse , handle patient ) {
2016-01-17 21:36:40 +00:00
if ( ! nurse | | ! patient )
2016-01-17 21:36:41 +00:00
pybind11_fail ( " Could not activate keep_alive! " ) ;
2016-01-17 21:36:39 +00:00
2016-08-29 01:38:47 +00:00
if ( patient . is_none ( ) | | nurse . is_none ( ) )
2016-08-16 05:50:43 +00:00
return ; /* Nothing to keep alive or nothing to be kept alive by */
2016-04-25 01:25:13 +00:00
2017-06-24 12:58:42 +00:00
auto tinfo = all_type_info ( Py_TYPE ( nurse . ptr ( ) ) ) ;
if ( ! tinfo . empty ( ) ) {
/* It's a pybind-registered type, so we can store the patient in the
* internal list . */
add_patient ( nurse . ptr ( ) , patient . ptr ( ) ) ;
}
else {
/* Fall back to clever approach based on weak references taken from
* Boost . Python . This is not used for pybind - registered types because
* the objects can be destroyed out - of - order in a GC pass . */
cpp_function disable_lifesupport (
[ patient ] ( handle weakref ) { patient . dec_ref ( ) ; weakref . dec_ref ( ) ; } ) ;
2016-01-17 21:36:39 +00:00
2017-06-24 12:58:42 +00:00
weakref wr ( nurse , disable_lifesupport ) ;
2016-01-17 21:36:39 +00:00
2017-06-24 12:58:42 +00:00
patient . inc_ref ( ) ; /* reference patient and leak the weak reference */
( void ) wr . release ( ) ;
}
2016-01-17 21:36:39 +00:00
}
PYBIND11_NOINLINE-related cleanup. (#3179)
* Removing pragma for GCC -Wattributes, fixing forward declarations.
* Introducing PYBIND11_NOINLINE_FWD to deal with CUDA, GCC7, GCC8.
* Updating PYBIND11_NOINLINE_DCL in Doxyfile.
* Trying noinline, noinline for {CUDA, GCC7, GCC8}
* Trying noinline, inline for {CUDA, GCC7, GCC8}
* Adding GCC -Wattributes `pragma` in 3 header files.
* Introducing PYBIND11_NOINLINE_GCC_PRAGMA_ATTRIBUTES_NEEDED, used in 9 header files.
* Removing ICC pragma 2196, to see if it is still needed.
* Trying noinline, noinline for ICC
* Trying noinline, inline for ICC
* Restoring ICC pragma 2196, introducing PYBIND11_NOINLINE_FORCED, defined for testing.
* Removing code accidentally left in (was for experimentation only).
* Removing one-time-test define.
* Removing PYBIND11_NOINLINE_FWD macro (after learning that it makes no sense).
* Testing with PYBIND11_NOINLINE_DISABLED. Minor non-functional enhancements.
* Removing #define PYBIND11_NOINLINE_DISABLED (test was successful).
* Removing PYBIND11_NOINLINE_FORCED and enhancing comments for PYBIND11_NOINLINE.
* WIP stripping back
* Making -Wattributes pragma in pybind11 specific to GCC7, GCC8, CUDA.
2021-08-09 17:10:38 +00:00
PYBIND11_NOINLINE void keep_alive_impl ( size_t Nurse , size_t Patient , function_call & call , handle ret ) {
2017-09-04 11:49:19 +00:00
auto get_arg = [ & ] ( size_t n ) {
if ( n = = 0 )
return ret ;
2021-07-09 13:45:53 +00:00
if ( n = = 1 & & call . init_self )
2017-09-04 11:49:19 +00:00
return call . init_self ;
2021-07-09 13:45:53 +00:00
if ( n < = call . args . size ( ) )
2017-09-04 11:49:19 +00:00
return call . args [ n - 1 ] ;
return handle ( ) ;
} ;
keep_alive_impl ( get_arg ( Nurse ) , get_arg ( Patient ) ) ;
2016-08-10 16:08:04 +00:00
}
2017-02-23 02:36:09 +00:00
inline std : : pair < decltype ( internals : : registered_types_py ) : : iterator , bool > all_type_info_get_cache ( PyTypeObject * type ) {
auto res = get_internals ( ) . registered_types_py
2017-07-29 07:53:45 +00:00
# ifdef __cpp_lib_unordered_map_try_emplace
2017-02-23 02:36:09 +00:00
. try_emplace ( type ) ;
# else
. emplace ( type , std : : vector < detail : : type_info * > ( ) ) ;
# endif
if ( res . second ) {
// New cache entry created; set up a weak reference to automatically remove it if the type
// gets destroyed:
weakref ( ( PyObject * ) type , cpp_function ( [ type ] ( handle wr ) {
get_internals ( ) . registered_types_py . erase ( type ) ;
2021-11-15 18:36:41 +00:00
// TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
auto & cache = get_internals ( ) . inactive_override_cache ;
for ( auto it = cache . begin ( ) , last = cache . end ( ) ; it ! = last ; ) {
if ( it - > first = = reinterpret_cast < PyObject * > ( type ) )
it = cache . erase ( it ) ;
else
+ + it ;
}
2017-02-23 02:36:09 +00:00
wr . dec_ref ( ) ;
} ) ) . release ( ) ;
}
return res ;
}
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
/* There are a large number of apparently unused template arguments because
* each combination requires a separate py : : class_ registration .
*/
template < typename Access , return_value_policy Policy , typename Iterator , typename Sentinel , typename ValueType , typename . . . Extra >
2016-08-24 22:29:04 +00:00
struct iterator_state {
Iterator it ;
Sentinel end ;
2017-06-09 14:49:04 +00:00
bool first_or_done ;
2016-06-17 21:29:39 +00:00
} ;
2016-04-13 21:33:00 +00:00
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
// Note: these helpers take the iterator by non-const reference because some
2021-10-11 15:35:39 +00:00
// iterators in the wild can't be dereferenced when const. The & after Iterator
// is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
// bugs in ICC, NVCC, and PGI compilers. See PR #3293.
template < typename Iterator , typename SFINAE = decltype ( * std : : declval < Iterator & > ( ) ) >
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
struct iterator_access {
2021-10-11 15:35:39 +00:00
using result_type = decltype ( * std : : declval < Iterator & > ( ) ) ;
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
// NOLINTNEXTLINE(readability-const-return-type) // PR #3263
result_type operator ( ) ( Iterator & it ) const {
return * it ;
}
} ;
Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
2021-09-21 17:37:19 +00:00
2021-10-11 15:35:39 +00:00
template < typename Iterator , typename SFINAE = decltype ( ( * std : : declval < Iterator & > ( ) ) . first ) >
class iterator_key_access {
private :
using pair_type = decltype ( * std : : declval < Iterator & > ( ) ) ;
public :
/* If either the pair itself or the element of the pair is a reference, we
* want to return a reference , otherwise a value . When the decltype
* expression is parenthesized it is based on the value category of the
* expression ; otherwise it is the declared type of the pair member .
* The use of declval < pair_type > in the second branch rather than directly
* using * std : : declval < Iterator & > ( ) is a workaround for nvcc
* ( it ' s not used in the first branch because going via decltype and back
* through declval does not perfectly preserve references ) .
*/
using result_type = conditional_t <
std : : is_reference < decltype ( * std : : declval < Iterator & > ( ) ) > : : value ,
decltype ( ( ( * std : : declval < Iterator & > ( ) ) . first ) ) ,
decltype ( std : : declval < pair_type > ( ) . first )
> ;
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
result_type operator ( ) ( Iterator & it ) const {
return ( * it ) . first ;
}
} ;
2021-10-11 15:35:39 +00:00
template < typename Iterator , typename SFINAE = decltype ( ( * std : : declval < Iterator & > ( ) ) . second ) >
class iterator_value_access {
private :
using pair_type = decltype ( * std : : declval < Iterator & > ( ) ) ;
public :
using result_type = conditional_t <
std : : is_reference < decltype ( * std : : declval < Iterator & > ( ) ) > : : value ,
decltype ( ( ( * std : : declval < Iterator & > ( ) ) . second ) ) ,
decltype ( std : : declval < pair_type > ( ) . second )
> ;
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
result_type operator ( ) ( Iterator & it ) const {
return ( * it ) . second ;
}
} ;
template < typename Access ,
return_value_policy Policy ,
2016-09-10 07:00:50 +00:00
typename Iterator ,
2016-08-24 22:29:04 +00:00
typename Sentinel ,
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
typename ValueType ,
2016-05-30 09:28:21 +00:00
typename . . . Extra >
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
iterator make_iterator_impl ( Iterator first , Sentinel last , Extra & & . . . extra ) {
using state = detail : : iterator_state < Access , Policy , Iterator , Sentinel , ValueType , Extra . . . > ;
// TODO: state captures only the types of Extra, not the values
2016-04-13 21:33:00 +00:00
2016-09-11 11:00:40 +00:00
if ( ! detail : : get_type_info ( typeid ( state ) , false ) ) {
2017-07-29 02:03:44 +00:00
class_ < state > ( handle ( ) , " iterator " , pybind11 : : module_local ( ) )
2016-04-13 21:33:00 +00:00
. def ( " __iter__ " , [ ] ( state & s ) - > state & { return s ; } )
2016-05-30 09:28:21 +00:00
. def ( " __next__ " , [ ] ( state & s ) - > ValueType {
2017-06-09 14:49:04 +00:00
if ( ! s . first_or_done )
2016-06-17 21:29:39 +00:00
+ + s . it ;
else
2017-06-09 14:49:04 +00:00
s . first_or_done = false ;
if ( s . it = = s . end ) {
s . first_or_done = true ;
2016-04-13 21:33:00 +00:00
throw stop_iteration ( ) ;
2017-06-09 14:49:04 +00:00
}
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
return Access ( ) ( s . it ) ;
2021-09-13 02:53:26 +00:00
// NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2016-09-10 07:00:50 +00:00
} , std : : forward < Extra > ( extra ) . . . , Policy ) ;
2016-04-13 21:33:00 +00:00
}
2017-06-09 14:49:04 +00:00
return cast ( state { first , last , true } ) ;
2016-04-13 21:33:00 +00:00
}
2016-09-06 04:06:31 +00:00
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
PYBIND11_NAMESPACE_END ( detail )
/// Makes a python iterator from a first and past-the-end C++ InputIterator.
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Iterator ,
typename Sentinel ,
typename ValueType = typename detail : : iterator_access < Iterator > : : result_type ,
typename . . . Extra >
iterator make_iterator ( Iterator first , Sentinel last , Extra & & . . . extra ) {
return detail : : make_iterator_impl <
detail : : iterator_access < Iterator > ,
Policy ,
Iterator ,
Sentinel ,
ValueType ,
Extra . . . > ( first , last , std : : forward < Extra > ( extra ) . . . ) ;
}
/// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
2017-03-18 16:34:21 +00:00
/// first and past-the-end InputIterator.
2016-09-10 07:00:50 +00:00
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Iterator ,
2016-08-24 22:29:04 +00:00
typename Sentinel ,
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
typename KeyType = typename detail : : iterator_key_access < Iterator > : : result_type ,
2016-08-12 01:22:05 +00:00
typename . . . Extra >
2021-09-10 04:27:36 +00:00
iterator make_key_iterator ( Iterator first , Sentinel last , Extra & & . . . extra ) {
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
return detail : : make_iterator_impl <
detail : : iterator_key_access < Iterator > ,
Policy ,
Iterator ,
Sentinel ,
KeyType ,
Extra . . . > ( first , last , std : : forward < Extra > ( extra ) . . . ) ;
}
2021-09-23 02:50:29 +00:00
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
/// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
/// first and past-the-end InputIterator.
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Iterator ,
typename Sentinel ,
typename ValueType = typename detail : : iterator_value_access < Iterator > : : result_type ,
typename . . . Extra >
iterator make_value_iterator ( Iterator first , Sentinel last , Extra & & . . . extra ) {
return detail : : make_iterator_impl <
detail : : iterator_value_access < Iterator > ,
Policy , Iterator ,
Sentinel ,
ValueType ,
Extra . . . > ( first , last , std : : forward < Extra > ( extra ) . . . ) ;
2016-08-12 01:22:05 +00:00
}
2016-04-13 21:33:00 +00:00
2017-03-18 16:34:21 +00:00
/// Makes an iterator over values of an stl container or other container supporting
/// `std::begin()`/`std::end()`
2016-09-10 07:00:50 +00:00
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Type , typename . . . Extra > iterator make_iterator ( Type & value , Extra & & . . . extra ) {
return make_iterator < Policy > ( std : : begin ( value ) , std : : end ( value ) , extra . . . ) ;
2016-04-18 08:52:12 +00:00
}
2017-03-18 16:34:21 +00:00
/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
/// `std::begin()`/`std::end()`
2016-09-10 07:00:50 +00:00
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Type , typename . . . Extra > iterator make_key_iterator ( Type & value , Extra & & . . . extra ) {
return make_key_iterator < Policy > ( std : : begin ( value ) , std : : end ( value ) , extra . . . ) ;
2016-08-12 01:22:05 +00:00
}
feat: reapply fixed version of #3271 (#3293)
* Add make_value_iterator (#3271)
* Add make_value_iterator
This is the counterpart to make_key_iterator, and will allow
implementing a `value` method in `bind_map` (although doing so is left
for a subsequent PR).
I made a few design changes to reduce copy-and-paste boilerplate.
Previously detail::iterator_state had a boolean template parameter to
indicate whether it was being used for make_iterator or
make_key_iterator. I replaced the boolean with a class that determines
how to dereference the iterator. This allows for a generic
implementation of `__next__`.
I also added the ValueType and Extra... parameters to the iterator_state
template args, because I think it was a bug that they were missing: if
make_iterator is called twice with different values of these, only the
first set has effect (because the state class is only registered once).
There is still a potential issue in that the *values* of the extra
arguments are latched on the first call, but since most policies are
empty classes this should be even less common.
* Add some remove_cv_t to appease clang-tidy
* Make iterator_access and friends take reference
For some reason I'd accidentally made it take a const value, which
caused some issues with third-party packages.
* Another attempt to remove remove_cv_t from iterators
Some of the return types were const (non-reference) types because of the
pecularities of decltype: `decltype((*it).first)` is the *declared* type
of the member of the pair, rather than the type of the expression. So if
the reference type of the iterator is `pair<const int, int> &`, then the
decltype is `const int`. Wrapping an extra set of parentheses to form
`decltype(((*it).first))` would instead give `const int &`.
This means that the existing make_key_iterator actually returns by value
from `__next__`, rather than by reference. Since for mapping types, keys
are always const, this probably hasn't been noticed, but it will affect
make_value_iterator if the Python code tries to mutate the returned
objects. I've changed things to use double parentheses so that
make_iterator, make_key_iterator and make_value_iterator should now all
return the reference type of the iterator. I'll still need to add a test
for that; for now I'm just checking whether I can keep Clang-Tidy happy.
* Add back some NOLINTNEXTLINE to appease Clang-Tidy
This is favoured over using remove_cv_t because in some cases a const
value return type is deliberate (particularly for Eigen).
* Add a unit test for iterator referencing
Ensure that make_iterator, make_key_iterator and make_value_iterator
return references to the container elements, rather than copies. The
test for make_key_iterator fails to compile on master, which gives me
confidence that this branch has fixed it.
* Make the iterator_access etc operator() const
I'm actually a little surprised it compiled at all given that the
operator() is called on a temporary, but I don't claim to fully
understand all the different value types in C++11.
* Attempt to work around compiler bugs
https://godbolt.org/ shows an example where ICC gets the wrong result
for a decltype used as the default for a template argument, and CI also
showed problems with PGI. This is a shot in the dark to see if it fixes
things.
* Make a test constructor explicit (Clang-Tidy)
* Fix unit test on GCC 4.8.5
It seems to require the arguments to the std::pair constructor to be
implicitly convertible to the types in the pair, rather than just
requiring is_constructible.
* Remove DOXYGEN_SHOULD_SKIP_THIS guards
Now that a complex decltype expression has been replaced by a simpler
nested type, I'm hoping Doxygen will be able to build it without issues.
* Add comment to explain iterator_state template params
* fix: regression in #3271
Co-authored-by: Bruce Merry <1963944+bmerry@users.noreply.github.com>
2021-09-23 19:06:07 +00:00
/// Makes an iterator over the values (`.second`) of a stl map-like container supporting
/// `std::begin()`/`std::end()`
template < return_value_policy Policy = return_value_policy : : reference_internal ,
typename Type , typename . . . Extra > iterator make_value_iterator ( Type & value , Extra & & . . . extra ) {
return make_value_iterator < Policy > ( std : : begin ( value ) , std : : end ( value ) , extra . . . ) ;
}
2015-07-05 18:05:44 +00:00
template < typename InputType , typename OutputType > void implicitly_convertible ( ) {
2017-08-28 14:34:06 +00:00
struct set_flag {
bool & flag ;
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
explicit set_flag ( bool & flag_ ) : flag ( flag_ ) { flag_ = true ; }
2017-08-28 14:34:06 +00:00
~ set_flag ( ) { flag = false ; }
} ;
moved processing of cpp_function arguments out of dispatch code
The cpp_function class accepts a variadic argument, which was formerly
processed twice -- once at registration time, and once in the dispatch
lambda function. This is not only unnecessarily slow but also leads to
code bloat since it adds to the object code generated for every bound
function. This change removes the second pass at dispatch time.
One noteworthy change of this commit is that default arguments are now
constructed (and converted to Python objects) right at declaration time.
Consider the following example:
py::class_<MyClass>("MyClass")
.def("myFunction", py::arg("arg") = SomeType(123));
In this case, the change means that pybind11 must already be set up to
deal with values of the type 'SomeType', or an exception will be thrown.
Another change is that the "preview" of the default argument in the
function signature is generated using the __repr__ special method. If
it is not available in this type, the signature may not be very helpful,
i.e.:
| myFunction(...)
| Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> None
One workaround (other than defining SomeType.__repr__) is to specify the
human-readable preview of the default argument manually using the more
cumbersome arg_t notation:
py::class_<MyClass>("MyClass")
.def("myFunction", py::arg_t<SomeType>("arg", SomeType(123), "SomeType(123)"));
2016-01-17 21:36:35 +00:00
auto implicit_caster = [ ] ( PyObject * obj , PyTypeObject * type ) - > PyObject * {
2017-08-28 14:34:06 +00:00
static bool currently_used = false ;
if ( currently_used ) // implicit conversions are non-reentrant
return nullptr ;
set_flag flag_helper ( currently_used ) ;
2017-01-03 10:52:05 +00:00
if ( ! detail : : make_caster < InputType > ( ) . load ( obj , false ) )
2015-07-05 18:05:44 +00:00
return nullptr ;
tuple args ( 1 ) ;
args [ 0 ] = obj ;
PyObject * result = PyObject_Call ( ( PyObject * ) type , args . ptr ( ) , nullptr ) ;
if ( result = = nullptr )
PyErr_Clear ( ) ;
return result ;
} ;
2016-10-23 14:43:03 +00:00
if ( auto tinfo = detail : : get_type_info ( typeid ( OutputType ) ) )
tinfo - > implicit_conversions . push_back ( implicit_caster ) ;
else
2016-01-17 21:36:41 +00:00
pybind11_fail ( " implicitly_convertible: Unable to find type " + type_id < OutputType > ( ) ) ;
2015-07-05 18:05:44 +00:00
}
2021-07-21 12:22:18 +00:00
inline void register_exception_translator ( ExceptionTranslator & & translator ) {
2016-06-17 21:35:59 +00:00
detail : : get_internals ( ) . registered_exception_translators . push_front (
std : : forward < ExceptionTranslator > ( translator ) ) ;
}
2021-07-21 12:22:18 +00:00
/**
* Add a new module - local exception translator . Locally registered functions
* will be tried before any globally registered exception translators , which
* will only be invoked if the module - local handlers do not deal with
* the exception .
*/
inline void register_local_exception_translator ( ExceptionTranslator & & translator ) {
detail : : get_local_internals ( ) . registered_exception_translators . push_front (
std : : forward < ExceptionTranslator > ( translator ) ) ;
}
2017-05-22 16:06:16 +00:00
/**
* Wrapper to generate a new Python exception type .
2016-06-17 21:35:59 +00:00
*
* This should only be used with PyErr_SetString for now .
* It is not ( yet ) possible to use as a py : : base .
* Template type argument is reserved for future use .
*/
template < typename type >
class exception : public object {
public :
2018-04-05 14:04:15 +00:00
exception ( ) = default ;
2020-09-15 14:24:39 +00:00
exception ( handle scope , const char * name , handle base = PyExc_Exception ) {
2016-11-16 16:59:56 +00:00
std : : string full_name = scope . attr ( " __name__ " ) . cast < std : : string > ( ) +
std : : string ( " . " ) + name ;
2020-09-15 14:24:39 +00:00
m_ptr = PyErr_NewException ( const_cast < char * > ( full_name . c_str ( ) ) , base . ptr ( ) , NULL ) ;
2020-10-08 23:09:56 +00:00
if ( hasattr ( scope , " __dict__ " ) & & scope . attr ( " __dict__ " ) . contains ( name ) )
2016-11-16 16:59:56 +00:00
pybind11_fail ( " Error during initialization: multiple incompatible "
" definitions with name \" " + std : : string ( name ) + " \" " ) ;
scope . attr ( name ) = * this ;
2016-06-17 21:35:59 +00:00
}
2016-09-16 06:04:15 +00:00
// Sets the current python exception to this exception object with the given message
void operator ( ) ( const char * message ) {
PyErr_SetString ( m_ptr , message ) ;
}
2016-06-17 21:35:59 +00:00
} ;
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
2018-04-05 14:04:15 +00:00
// Returns a reference to a function-local static exception object used in the simple
// register_exception approach below. (It would be simpler to have the static local variable
// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
template < typename CppException >
exception < CppException > & get_exception_object ( ) { static exception < CppException > ex ; return ex ; }
2021-07-21 12:22:18 +00:00
// Helper function for register_exception and register_local_exception
2016-11-16 16:59:56 +00:00
template < typename CppException >
2021-07-21 12:22:18 +00:00
exception < CppException > & register_exception_impl ( handle scope ,
const char * name ,
handle base ,
bool isLocal ) {
2018-04-05 14:04:15 +00:00
auto & ex = detail : : get_exception_object < CppException > ( ) ;
if ( ! ex ) ex = exception < CppException > ( scope , name , base ) ;
2021-07-21 12:22:18 +00:00
auto register_func = isLocal ? & register_local_exception_translator
: & register_exception_translator ;
register_func ( [ ] ( std : : exception_ptr p ) {
2016-09-16 06:04:15 +00:00
if ( ! p ) return ;
try {
std : : rethrow_exception ( p ) ;
2016-11-16 16:59:56 +00:00
} catch ( const CppException & e ) {
2018-04-05 14:04:15 +00:00
detail : : get_exception_object < CppException > ( ) ( e . what ( ) ) ;
2016-09-16 06:04:15 +00:00
}
} ) ;
return ex ;
}
2021-07-21 12:22:18 +00:00
PYBIND11_NAMESPACE_END ( detail )
/**
* Registers a Python exception in ` m ` of the given ` name ` and installs a translator to
* translate the C + + exception to the created Python exception using the what ( ) method .
* This is intended for simple exception translations ; for more complex translation , register the
* exception object and translator directly .
*/
template < typename CppException >
exception < CppException > & register_exception ( handle scope ,
const char * name ,
handle base = PyExc_Exception ) {
return detail : : register_exception_impl < CppException > ( scope , name , base , false /* isLocal */ ) ;
}
/**
* Registers a Python exception in ` m ` of the given ` name ` and installs a translator to
* translate the C + + exception to the created Python exception using the what ( ) method .
* This translator will only be used for exceptions that are thrown in this module and will be
* tried before global exception translators , including those registered with register_exception .
* This is intended for simple exception translations ; for more complex translation , register the
* exception object and translator directly .
*/
template < typename CppException >
exception < CppException > & register_local_exception ( handle scope ,
const char * name ,
handle base = PyExc_Exception ) {
return detail : : register_exception_impl < CppException > ( scope , name , base , true /* isLocal */ ) ;
}
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
PYBIND11_NOINLINE-related cleanup. (#3179)
* Removing pragma for GCC -Wattributes, fixing forward declarations.
* Introducing PYBIND11_NOINLINE_FWD to deal with CUDA, GCC7, GCC8.
* Updating PYBIND11_NOINLINE_DCL in Doxyfile.
* Trying noinline, noinline for {CUDA, GCC7, GCC8}
* Trying noinline, inline for {CUDA, GCC7, GCC8}
* Adding GCC -Wattributes `pragma` in 3 header files.
* Introducing PYBIND11_NOINLINE_GCC_PRAGMA_ATTRIBUTES_NEEDED, used in 9 header files.
* Removing ICC pragma 2196, to see if it is still needed.
* Trying noinline, noinline for ICC
* Trying noinline, inline for ICC
* Restoring ICC pragma 2196, introducing PYBIND11_NOINLINE_FORCED, defined for testing.
* Removing code accidentally left in (was for experimentation only).
* Removing one-time-test define.
* Removing PYBIND11_NOINLINE_FWD macro (after learning that it makes no sense).
* Testing with PYBIND11_NOINLINE_DISABLED. Minor non-functional enhancements.
* Removing #define PYBIND11_NOINLINE_DISABLED (test was successful).
* Removing PYBIND11_NOINLINE_FORCED and enhancing comments for PYBIND11_NOINLINE.
* WIP stripping back
* Making -Wattributes pragma in pybind11 specific to GCC7, GCC8, CUDA.
2021-08-09 17:10:38 +00:00
PYBIND11_NOINLINE void print ( const tuple & args , const dict & kwargs ) {
2016-08-29 16:03:34 +00:00
auto strings = tuple ( args . size ( ) ) ;
for ( size_t i = 0 ; i < args . size ( ) ; + + i ) {
2016-10-25 20:12:39 +00:00
strings [ i ] = str ( args [ i ] ) ;
2016-08-29 16:03:34 +00:00
}
2016-09-20 23:06:32 +00:00
auto sep = kwargs . contains ( " sep " ) ? kwargs [ " sep " ] : cast ( " " ) ;
2016-09-08 15:02:04 +00:00
auto line = sep . attr ( " join " ) ( strings ) ;
2016-08-29 16:03:34 +00:00
2016-10-13 08:34:52 +00:00
object file ;
if ( kwargs . contains ( " file " ) ) {
file = kwargs [ " file " ] . cast < object > ( ) ;
} else {
try {
2020-10-03 17:38:03 +00:00
file = module_ : : import ( " sys " ) . attr ( " stdout " ) ;
2016-12-01 10:35:34 +00:00
} catch ( const error_already_set & ) {
2016-10-13 08:34:52 +00:00
/* If print() is called from code that is executed as
part of garbage collection during interpreter shutdown ,
importing ' sys ' can fail . Give up rather than crashing the
interpreter in this case . */
return ;
}
}
2016-09-08 15:02:04 +00:00
auto write = file . attr ( " write " ) ;
2016-08-29 16:03:34 +00:00
write ( line ) ;
2016-09-20 23:06:32 +00:00
write ( kwargs . contains ( " end " ) ? kwargs [ " end " ] : cast ( " \n " ) ) ;
2016-08-29 16:03:34 +00:00
2016-10-13 08:34:52 +00:00
if ( kwargs . contains ( " flush " ) & & kwargs [ " flush " ] . cast < bool > ( ) )
2016-09-08 15:02:04 +00:00
file . attr ( " flush " ) ( ) ;
2016-08-29 16:03:34 +00:00
}
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_END ( detail )
2016-08-29 16:03:34 +00:00
template < return_value_policy policy = return_value_policy : : automatic_reference , typename . . . Args >
void print ( Args & & . . . args ) {
auto c = detail : : collect_arguments < policy > ( std : : forward < Args > ( args ) . . . ) ;
detail : : print ( c . args ( ) , c . kwargs ( ) ) ;
}
2016-11-24 22:11:02 +00:00
error_already_set : : ~ error_already_set ( ) {
2019-05-03 12:32:28 +00:00
if ( m_type ) {
2016-11-24 22:11:02 +00:00
gil_scoped_acquire gil ;
2019-07-06 12:52:32 +00:00
error_scope scope ;
2019-05-03 12:32:28 +00:00
m_type . release ( ) . dec_ref ( ) ;
m_value . release ( ) . dec_ref ( ) ;
m_trace . release ( ) . dec_ref ( ) ;
2016-11-24 22:11:02 +00:00
}
}
2020-09-15 12:56:20 +00:00
PYBIND11_NAMESPACE_BEGIN ( detail )
inline function get_type_override ( const void * this_ptr , const type_info * this_type , const char * name ) {
handle self = get_object_handle ( this_ptr , this_type ) ;
2016-12-16 14:00:46 +00:00
if ( ! self )
2015-10-01 16:37:26 +00:00
return function ( ) ;
2020-09-16 15:32:17 +00:00
handle type = type : : handle_of ( self ) ;
2015-10-01 14:46:03 +00:00
auto key = std : : make_pair ( type . ptr ( ) , name ) ;
2020-09-15 12:56:20 +00:00
/* Cache functions that aren't overridden in Python to avoid
2016-04-11 16:13:08 +00:00
many costly Python dictionary lookups below */
2020-09-15 12:56:20 +00:00
auto & cache = get_internals ( ) . inactive_override_cache ;
2015-10-01 14:46:03 +00:00
if ( cache . find ( key ) ! = cache . end ( ) )
return function ( ) ;
2020-09-15 12:56:20 +00:00
function override = getattr ( self , name , function ( ) ) ;
if ( override . is_cpp_function ( ) ) {
2015-10-01 14:46:03 +00:00
cache . insert ( key ) ;
return function ( ) ;
}
2016-01-17 21:36:37 +00:00
2016-12-16 14:00:46 +00:00
/* Don't call dispatch code if invoked from overridden function.
Unfortunately this doesn ' t work on PyPy . */
2021-11-17 14:44:19 +00:00
# if !defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000
// TODO: Remove PyPy workaround for Python 3.11.
// Current API fails on 3.11 since co_varnames can be null.
2021-10-26 18:50:34 +00:00
# if PY_VERSION_HEX >= 0x03090000
PyFrameObject * frame = PyThreadState_GetFrame ( PyThreadState_Get ( ) ) ;
if ( frame ! = nullptr ) {
PyCodeObject * f_code = PyFrame_GetCode ( frame ) ;
// f_code is guaranteed to not be NULL
if ( ( std : : string ) str ( f_code - > co_name ) = = name & & f_code - > co_argcount > 0 ) {
PyObject * locals = PyEval_GetLocals ( ) ;
2021-11-17 14:44:19 +00:00
if ( locals ! = nullptr & & f_code - > co_varnames ! = nullptr ) {
2021-10-26 18:50:34 +00:00
PyObject * self_caller = dict_getitem (
locals , PyTuple_GET_ITEM ( f_code - > co_varnames , 0 )
) ;
if ( self_caller = = self . ptr ( ) ) {
Py_DECREF ( f_code ) ;
Py_DECREF ( frame ) ;
return function ( ) ;
}
}
}
Py_DECREF ( f_code ) ;
Py_DECREF ( frame ) ;
}
# else
2015-10-01 14:46:03 +00:00
PyFrameObject * frame = PyThreadState_Get ( ) - > frame ;
2021-07-27 22:32:26 +00:00
if ( frame ! = nullptr & & ( std : : string ) str ( frame - > f_code - > co_name ) = = name
& & frame - > f_code - > co_argcount > 0 ) {
2016-04-11 16:13:08 +00:00
PyFrame_FastToLocals ( frame ) ;
2021-07-02 14:02:33 +00:00
PyObject * self_caller = dict_getitem (
2016-04-11 16:13:08 +00:00
frame - > f_locals , PyTuple_GET_ITEM ( frame - > f_code - > co_varnames , 0 ) ) ;
2016-12-16 14:00:46 +00:00
if ( self_caller = = self . ptr ( ) )
2016-04-11 16:13:08 +00:00
return function ( ) ;
}
2021-10-26 18:50:34 +00:00
# endif
2016-12-16 14:00:46 +00:00
# else
/* PyPy currently doesn't provide a detailed cpyext emulation of
frame objects , so we have to emulate this using Python . This
is going to be slow . . */
dict d ; d [ " self " ] = self ; d [ " name " ] = pybind11 : : str ( name ) ;
PyObject * result = PyRun_String (
" import inspect \n "
" frame = inspect.currentframe() \n "
" if frame is not None: \n "
" frame = frame.f_back \n "
" if frame is not None and str(frame.f_code.co_name) == name and "
" frame.f_code.co_argcount > 0: \n "
" self_caller = frame.f_locals[frame.f_code.co_varnames[0]] \n "
" if self_caller == self: \n "
" self = None \n " ,
Py_file_input , d . ptr ( ) , d . ptr ( ) ) ;
if ( result = = nullptr )
throw error_already_set ( ) ;
2017-02-08 00:01:56 +00:00
if ( d [ " self " ] . is_none ( ) )
2016-12-16 14:00:46 +00:00
return function ( ) ;
Py_DECREF ( result ) ;
# endif
2020-09-15 12:56:20 +00:00
return override ;
2015-10-01 14:46:03 +00:00
}
2020-09-15 12:56:20 +00:00
PYBIND11_NAMESPACE_END ( detail )
2015-10-01 14:46:03 +00:00
2019-06-10 20:12:28 +00:00
/** \rst
Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr .
2021-01-14 04:15:58 +00:00
: this_ptr : The pointer to the object the overridden method should be retrieved for . This should be
2020-09-15 12:56:20 +00:00
the first non - trampoline class encountered in the inheritance chain .
: name : The name of the overridden Python method to retrieve .
2019-06-10 20:12:28 +00:00
: return : The Python method by this name from the object or an empty function wrapper .
\ endrst */
2020-09-15 12:56:20 +00:00
template < class T > function get_override ( const T * this_ptr , const char * name ) {
2016-10-23 14:43:03 +00:00
auto tinfo = detail : : get_type_info ( typeid ( T ) ) ;
2020-09-15 12:56:20 +00:00
return tinfo ? detail : : get_type_override ( this_ptr , tinfo , name ) : function ( ) ;
2016-08-09 21:57:59 +00:00
}
2021-07-09 13:45:53 +00:00
# define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
do { \
pybind11 : : gil_scoped_acquire gil ; \
pybind11 : : function override \
= pybind11 : : get_override ( static_cast < const cname * > ( this ) , name ) ; \
if ( override ) { \
auto o = override ( __VA_ARGS__ ) ; \
if ( pybind11 : : detail : : cast_is_temporary_value_reference < ret_type > : : value ) { \
static pybind11 : : detail : : override_caster_t < ret_type > caster ; \
return pybind11 : : detail : : cast_ref < ret_type > ( std : : move ( o ) , caster ) ; \
} \
return pybind11 : : detail : : cast_safe < ret_type > ( std : : move ( o ) ) ; \
} \
2020-09-15 12:56:20 +00:00
} while ( false )
2015-10-01 14:46:03 +00:00
2019-06-10 20:12:28 +00:00
/** \rst
Macro to populate the virtual method in the trampoline class . This macro tries to look up a method named ' fn '
from the Python side , deals with the : ref : ` gil ` and necessary argument conversions to call this method and return
the appropriate type . See : ref : ` overriding_virtuals ` for more information . This macro should be used when the method
name in C is not the same as the method name in Python . For example with ` __str__ ` .
. . code - block : : cpp
std : : string toString ( ) override {
2020-09-15 12:56:20 +00:00
PYBIND11_OVERRIDE_NAME (
2019-06-10 20:12:28 +00:00
std : : string , // Return type (ret_type)
Animal , // Parent class (cname)
2020-06-15 19:34:45 +00:00
" __str__ " , // Name of method in Python (name)
toString , // Name of function in C++ (fn)
2019-06-10 20:12:28 +00:00
) ;
}
\ endrst */
2020-09-15 12:56:20 +00:00
# define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
do { \
PYBIND11_OVERRIDE_IMPL ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , name , __VA_ARGS__ ) ; \
return cname : : fn ( __VA_ARGS__ ) ; \
} while ( false )
2015-10-01 14:46:03 +00:00
2019-06-10 20:12:28 +00:00
/** \rst
2020-09-15 12:56:20 +00:00
Macro for pure virtual functions , this function is identical to : c : macro : ` PYBIND11_OVERRIDE_NAME ` , except that it
throws if no override can be found .
2019-06-10 20:12:28 +00:00
\ endrst */
2020-09-15 12:56:20 +00:00
# define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
do { \
PYBIND11_OVERRIDE_IMPL ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , name , __VA_ARGS__ ) ; \
pybind11 : : pybind11_fail ( " Tried to call pure virtual function \" " PYBIND11_STRINGIFY ( cname ) " :: " name " \" " ) ; \
} while ( false )
2016-05-24 21:42:05 +00:00
2019-06-10 20:12:28 +00:00
/** \rst
Macro to populate the virtual method in the trampoline class . This macro tries to look up the method
from the Python side , deals with the : ref : ` gil ` and necessary argument conversions to call this method and return
the appropriate type . This macro should be used if the method name in C and in Python are identical .
See : ref : ` overriding_virtuals ` for more information .
. . code - block : : cpp
class PyAnimal : public Animal {
public :
// Inherit the constructors
using Animal : : Animal ;
// Trampoline (need one for each virtual function)
std : : string go ( int n_times ) override {
2020-09-15 12:56:20 +00:00
PYBIND11_OVERRIDE_PURE (
2019-06-10 20:12:28 +00:00
std : : string , // Return type (ret_type)
Animal , // Parent class (cname)
go , // Name of function in C++ (must match Python name) (fn)
n_times // Argument(s) (...)
) ;
}
} ;
\ endrst */
2020-09-15 12:56:20 +00:00
# define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
PYBIND11_OVERRIDE_NAME ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , # fn , fn , __VA_ARGS__ )
2016-05-24 21:42:05 +00:00
2019-06-10 20:12:28 +00:00
/** \rst
2020-09-15 12:56:20 +00:00
Macro for pure virtual functions , this function is identical to : c : macro : ` PYBIND11_OVERRIDE ` , except that it throws
if no override can be found .
2019-06-10 20:12:28 +00:00
\ endrst */
2020-09-15 12:56:20 +00:00
# define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
PYBIND11_OVERRIDE_PURE_NAME ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , # fn , fn , __VA_ARGS__ )
// Deprecated versions
PYBIND11_DEPRECATED ( " get_type_overload has been deprecated " )
inline function get_type_overload ( const void * this_ptr , const detail : : type_info * this_type , const char * name ) {
return detail : : get_type_override ( this_ptr , this_type , name ) ;
}
template < class T >
inline function get_overload ( const T * this_ptr , const char * name ) {
return get_override ( this_ptr , name ) ;
}
# define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
PYBIND11_OVERRIDE_IMPL ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , name , __VA_ARGS__ )
# define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
PYBIND11_OVERRIDE_NAME ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , name , fn , __VA_ARGS__ )
# define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
PYBIND11_OVERRIDE_PURE_NAME ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , name , fn , __VA_ARGS__ ) ;
# define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
PYBIND11_OVERRIDE ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , fn , __VA_ARGS__ )
2016-05-24 21:42:05 +00:00
# define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2020-09-15 12:56:20 +00:00
PYBIND11_OVERRIDE_PURE ( PYBIND11_TYPE ( ret_type ) , PYBIND11_TYPE ( cname ) , fn , __VA_ARGS__ ) ;
2015-10-01 14:46:03 +00:00
2020-07-08 22:14:41 +00:00
PYBIND11_NAMESPACE_END ( PYBIND11_NAMESPACE )
2015-07-05 18:05:44 +00:00
2021-07-30 14:09:55 +00:00
# if defined(__GNUC__) && __GNUC__ == 7
# pragma GCC diagnostic pop // -Wnoexcept-type
# endif