* Adding PyGILState_Check() in object_api<>::operator().
* Enabling PyGILState_Check() for Python >= 3.6 only.
Possibly, this explains why PyGILState_Check() cannot safely be used with Python 3.4 and 3.5:
https://github.com/python/cpython/pull/10267#issuecomment-434881587
* Adding simple micro benchmark.
* Reducing test time to minimum (purely for coverage, not for accurate results).
* Fixing silly oversight.
* Minor code organization improvement in test.
* Adding example runtimes.
* Removing capsys (just run with `-k test_callback_num_times -s` and using `.format()`.
* Use correct duration representation when casting from datetime.timdelta to std::chrono::duration
* When asserting datetime/timedelta/date/time we can equality-compare whole objects
* [dtype]: add type() method to access type attribute of PyArray_Descr (eq. to dtype.char in Python)
* [dtype] change type() name method to char_() to be compliant with Python numpy interface
* [dtype] fix by pre-commit
* [dtype] Change comments and solutions format for test
* Clarify documentation and move note about dtype.char vs PyArray_Descr::type to a plain, non-doxygen comment
* Fix and extend tests
* Fix the supposedly fixed tests
* Fix the fixed tests again
Co-authored-by: Bertrand MICHEL <bertrand.michel@onera.fr>
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
* Demonstrate issue with weakref constructor overloads
* Fix weakref constructor to convert on being passed a non-weakref object
* Improve on nonlocal-scoped variable in test_weakref
* Keep backwards-compatibility by introducing PYBIND11_OBJECT_CVT_DEFAULT macro
* Simplify test_weakref
* Adding move_only_holder_caster `typename SFINAE = void` to enable external specializations.
* Adding SFINAE hook also to copyable_holder_caster, for uniformity, with comment to explain the purpose.
* When determining if a shared_ptr already exists, use a test on the weak_ptr instead of a try/catch block.
* When determining if a shared_ptr already exists, use a test on the weak_ptr instead of a try/catch block.
* weak_from_this is only available in C++17 and later
* Switch to use feature flag instead of C++ version flag.
* Add Microsoft-specific check.
* Avoid undefined preprocessor macro warning treated as error.
* Simplify shared_from_this in init_holder
* Include <version> in detail/common.h (~stolen~ borrowed from @bstaletic's #2816)
* Move class_::get_shared_from_this to detail::try_get_shared_from_this
* Simplify try_get_shared_from_this by using weak_ptr::lock()
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
* Always call PyNumber_Index when casting from Python to a C++ integral type, also pre-3.8
* Fixed on PyPy
* Simplify use of PyNumber_Index, following @rwgk's idea, and ignore warnings in >=3.8
* Reproduce mismatch between pre-3.8 and post-3.8 behavior on __index__ throwing TypeError
* Fix tests on 3.6 <= Python < 3.8
* No, I don't have an uninitialized variable
* Fix use of __index__ on Python 2
* Make types in test_int_convert more ~boring~ descriptive
* Force the builtin module key to be the correct type.
Previously it was always going to be a std::string which converted into
unicode. Python 2 appears to want module keys to be normal str types, so
this was breaking code that expected plain string types in the
builtins.keys() data structure
* Add a simple unit test to ensure all built-in keys are str
* Update the unit test so it will also run on pypy
* Run pre-commit.
Co-authored-by: Jesse Clemens <jesse.clemens@sony.com>
* CI: Intel icc/icpc via oneAPI
Add testing for Intel icc/icpc via the oneAPI images.
Intel oneAPI is in a late beta stage, currently shipping
oneAPI beta09 with ICC 20.2.
CI: Skip Interpreter Tests for Intel
Cannot find how to add this, neiter the package `libc6-dev` nor
`intel-oneapi-mkl-devel` help when installed to solve this:
```
-- Looking for C++ include pthread.h
-- Looking for C++ include pthread.h - not found
CMake Error at /__t/cmake/3.18.4/x64/cmake-3.18.4-Linux-x86_64/share/cmake-3.18/Modules/FindPackageHandleStandardArgs.cmake:165 (message):
Could NOT find Threads (missing: Threads_FOUND)
Call Stack (most recent call first):
/__t/cmake/3.18.4/x64/cmake-3.18.4-Linux-x86_64/share/cmake-3.18/Modules/FindPackageHandleStandardArgs.cmake:458 (_FPHSA_FAILURE_MESSAGE)
/__t/cmake/3.18.4/x64/cmake-3.18.4-Linux-x86_64/share/cmake-3.18/Modules/FindThreads.cmake:234 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
tests/test_embed/CMakeLists.txt:17 (find_package)
```
CI: libc6-dev from GCC for ICC
CI: Run bare metal for oneAPI
CI: Ubuntu 18.04 for oneAPI
CI: Intel +Catch -Eigen
CI: CMake from Apt (ICC tests)
CI: Replace Intel Py with GCC Py
CI: Intel w/o GCC's Eigen
CI: ICC with verbose make
[Debug] Find core dump
tests: use arg{} instead of arg() for Intel
tests: adding a few more missing {}
fix: sync with @tobiasleibner's branch
fix: try ubuntu 20-04
fix: drop exit 1
docs: Apply suggestions from code review
Co-authored-by: Tobias Leibner <tobias.leibner@googlemail.com>
Workaround for ICC enable_if issues
Another workaround for ICC's enable_if issues
fix error in previous commit
Disable one test for the Intel compiler in C++17 mode
Add back one instance of py::arg().noconvert()
Add NOLINT to fix clang-tidy check
Work around for ICC internal error in PYBIND11_EXPAND_SIDE_EFFECTS in C++17 mode
CI: Intel ICC with C++17
docs: pybind11/numpy.h does not require numpy at build time. (#2720)
This is nice enough to be mentioned explicitly in the docs.
docs: Update warning about Python 3.9.0 UB, now that 3.9.1 has been released (#2719)
Adjusting `type_caster<std::reference_wrapper<T>>` to support const/non-const propagation in `cast_op`. (#2705)
* Allow type_caster of std::reference_wrapper<T> to be the same as a native reference.
Before, both std::reference_wrapper<T> and std::reference_wrapper<const T> would
invoke cast_op<type>. This doesn't allow the type_caster<> specialization for T
to distinguish reference_wrapper types from value types.
After, the type_caster<> specialization invokes cast_op<type&>, which allows
reference_wrapper to behave in the same way as a native reference type.
* Add tests/examples for std::reference_wrapper<const T>
* Add tests which use mutable/immutable variants
This test is a chimera; it blends the pybind11 casters with a custom
pytype implementation that supports immutable and mutable calls.
In order to detect the immutable/mutable state, the cast_op needs
to propagate it, even through e.g. std::reference<const T>
Note: This is still a work in progress; some things are crashing,
which likely means that I have a refcounting bug or something else
missing.
* Add/finish tests that distinguish const& from &
Fixes the bugs in my custom python type implementation,
demonstrate test that requires const& and reference_wrapper<const T>
being treated differently from Non-const.
* Add passing a const to non-const method.
* Demonstrate non-const conversion of reference_wrapper in tests.
Apply formatting presubmit check.
* Fix build errors from presubmit checks.
* Try and fix a few more CI errors
* More CI fixes.
* More CI fixups.
* Try and get PyPy to work.
* Additional minor fixups. Getting close to CI green.
* More ci fixes?
* fix clang-tidy warnings from presubmit
* fix more clang-tidy warnings
* minor comment and consistency cleanups
* PyDECREF -> Py_DECREF
* copy/move constructors
* Resolve codereview comments
* more review comment fixes
* review comments: remove spurious &
* Make the test fail even when the static_assert is commented out.
This expands the test_freezable_type_caster a bit by:
1/ adding accessors .is_immutable and .addr to compare identity
from python.
2/ Changing the default cast_op of the type_caster<> specialization
to return a non-const value. In normal codepaths this is a reasonable
default.
3/ adding roundtrip variants to exercise the by reference, by pointer
and by reference_wrapper in all call paths. In conjunction with 2/, this
demonstrates the failure case of the existing std::reference_wrpper conversion,
which now loses const in a similar way that happens when using the default cast_op_type<>.
* apply presubmit formatting
* Revert inclusion of test_freezable_type_caster
There's some concern that this test is a bit unwieldly because of the use
of the raw <Python.h> functions. Removing for now.
* Add a test that validates const references propagation.
This test verifies that cast_op may be used to correctly detect
const reference types when used with std::reference_wrapper.
* mend
* Review comments based changes.
1. std::add_lvalue_reference<type> -> type&
2. Simplify the test a little more; we're never returning the ConstRefCaster
type so the class_ definition can be removed.
* formatted files again.
* Move const_ref_caster test to builtin_casters
* Review comments: use cast_op and adjust some comments.
* Simplify ConstRefCasted test
I like this version better as it moves the assertion that matters
back into python.
ci: drop pypy2 linux, PGI 20.7, add Python 10 dev (#2724)
* ci: drop pypy2 linux, add Python 10 dev
* ci: fix mistake
* ci: commented-out PGI 20.11, drop 20.7
fix: regression with installed pybind11 overriding local one (#2716)
* fix: regression with installed pybind11 overriding discovered one
Closes#2709
* docs: wording incorrect
style: remove redundant instance->owned = true (#2723)
which was just before set to True in instance->allocate_layout()
fix: also throw in the move-constructor added by the PYBIND11_OBJECT macro, after the argument has been moved-out (if necessary) (#2701)
Make args_are_all_* ICC workarounds unconditional
Disable test_aligned on Intel ICC
Fix test_aligned on Intel ICC
Skip test_python_alreadyset_in_destructor on Intel ICC
Fix test_aligned again
ICC CI: Downgrade pytest
pytest 6 does not capture the `discard_as_unraisable` stderr and
just writes a warning with its content instead.
* refactor: simpler Intel workaround, suggested by @laramiel
* fix: try version with impl to see if it is easier to compile
* docs: update README for ICC
Co-authored-by: Axel Huebl <axel.huebl@plasma.ninja>
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* Only allow integer type_caster to call __int__ or __index__ method when conversion is allowed
* Remove tests for __index__ as this seems to only be used to convert to int in 3.8+
* Take both `int` and `long` types into account for Python 2
* Add test_numpy_int_convert to assert tests currently fail, even though np.intc has an __index__ method
* Also consider __index__ as noconvert to a C++ integer
* New-style classes for Python 2.7; sigh
* Add some tests on types with custom __index__ method
* Ignore some tests in Python <3.8
* Update comment about conversion from np.float32 to C++ int
* Workaround difference between CPython and PyPy's different PyIndex_Check (unnoticed because we currently don't have PyPy >= 3.8)
* Avoid ICC segfault with py::arg()
* Plug leaking function_record objects when exceptions are thrown
* Plug leak of strdup'ed strings in function_record
* Some extra comments about the function_record ownership dance
* Clean up the function_record better, in case of exceptions
* Demonstrate some extra function_record leaks
* Change DeleteStrings template argument to free_strings runtime argument in destruct(function_record *)
* Zero-state unique_function_record deleter object
* Clarify rvalue reference to unique_ptr parameter in initialize_generic
* Use push_back with const char * instead of emplace_back
* Fix a clang warning from [-Wshadow-field-in-constructor-modified]
warning: modifying constructor parameter 'flag' that shadows a field of 'set_flag' [-Wshadow-field-in-constructor-modified]
* Change name based on review
* Update attr.h: fix a warning found by static code analyzer
Update attr.h: fix a warning found by Visual Studio static code analyzer
Severity:Warning
Code:C6323
Description: Use of arithmetic operator on Boolean type(s).
Location: C:\src\onnxruntime\debug\pybind11\src\pybind11\include\pybind11\attr.h:547
* Update include/pybind11/attr.h
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
* Update attr.h
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
* Fix leak in the test_copy_move::test_move_fallback
* Fix leaking PyMethodDef in test_class::test_implicit_conversion_life_support
* Plumb leak in test_buffer, occuring when a mutable buffer is requested for a read-only object, and enable test_buffer.py
* Fix weird return_value_policy::reference in test_stl_binders, and enable those tests
* Cleanup nodelete holder objects in test_smart_ptr, and enable those tests
* Avoid thread termination in scoped_released
Do not call `PyEval_RestoreThread()` from `~gil_scoped_release()` if python runtime is finalizing, as it will result in thread termination in Python runtime newer than 3.6, as documented in https://docs.python.org/3/c-api/init.html#c.PyEval_RestoreThread
Similarly do not call `PyThreadState_DeleteCurrent` from `~gil_scoped_acquire()` if runtime is finalizing.
Discovered while debugging PyTorch crash using Python-3.9 described in https://github.com/pytorch/pytorch/issues/47776
* Simplify _Py_IsFinalizing() availability check
* Fix typo
* Add version agnostic `detail::finalization_guard()`
* Move `finalization_guard` to detail/common.h
And rename it to `is_finalizing`
* Move `is_finalizing()` back to pybind11.h
* Simplify `is_finalizing()` check
One should follow documentation rather than make any assumptions
* feat: disarm
* docs: fix comment
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* Allow type_caster of std::reference_wrapper<T> to be the same as a native reference.
Before, both std::reference_wrapper<T> and std::reference_wrapper<const T> would
invoke cast_op<type>. This doesn't allow the type_caster<> specialization for T
to distinguish reference_wrapper types from value types.
After, the type_caster<> specialization invokes cast_op<type&>, which allows
reference_wrapper to behave in the same way as a native reference type.
* Add tests/examples for std::reference_wrapper<const T>
* Add tests which use mutable/immutable variants
This test is a chimera; it blends the pybind11 casters with a custom
pytype implementation that supports immutable and mutable calls.
In order to detect the immutable/mutable state, the cast_op needs
to propagate it, even through e.g. std::reference<const T>
Note: This is still a work in progress; some things are crashing,
which likely means that I have a refcounting bug or something else
missing.
* Add/finish tests that distinguish const& from &
Fixes the bugs in my custom python type implementation,
demonstrate test that requires const& and reference_wrapper<const T>
being treated differently from Non-const.
* Add passing a const to non-const method.
* Demonstrate non-const conversion of reference_wrapper in tests.
Apply formatting presubmit check.
* Fix build errors from presubmit checks.
* Try and fix a few more CI errors
* More CI fixes.
* More CI fixups.
* Try and get PyPy to work.
* Additional minor fixups. Getting close to CI green.
* More ci fixes?
* fix clang-tidy warnings from presubmit
* fix more clang-tidy warnings
* minor comment and consistency cleanups
* PyDECREF -> Py_DECREF
* copy/move constructors
* Resolve codereview comments
* more review comment fixes
* review comments: remove spurious &
* Make the test fail even when the static_assert is commented out.
This expands the test_freezable_type_caster a bit by:
1/ adding accessors .is_immutable and .addr to compare identity
from python.
2/ Changing the default cast_op of the type_caster<> specialization
to return a non-const value. In normal codepaths this is a reasonable
default.
3/ adding roundtrip variants to exercise the by reference, by pointer
and by reference_wrapper in all call paths. In conjunction with 2/, this
demonstrates the failure case of the existing std::reference_wrpper conversion,
which now loses const in a similar way that happens when using the default cast_op_type<>.
* apply presubmit formatting
* Revert inclusion of test_freezable_type_caster
There's some concern that this test is a bit unwieldly because of the use
of the raw <Python.h> functions. Removing for now.
* Add a test that validates const references propagation.
This test verifies that cast_op may be used to correctly detect
const reference types when used with std::reference_wrapper.
* mend
* Review comments based changes.
1. std::add_lvalue_reference<type> -> type&
2. Simplify the test a little more; we're never returning the ConstRefCaster
type so the class_ definition can be removed.
* formatted files again.
* Move const_ref_caster test to builtin_casters
* Review comments: use cast_op and adjust some comments.
* Simplify ConstRefCasted test
I like this version better as it moves the assertion that matters
back into python.
This line had two bugs:
1. It declares `py::detail::class_` as `friend`.
2. After fixing that, we would have to change it to
`template <typename, typename...>`
The first one was introduced ~5 years ago, when a large refactoring was
made, probably as an intermediate step during refactoring.
The second was made when `generic_type` was made to be agnostic with
respect to the order of `py::class_` template parameters.
We're removing the declaration altogether, because it was never relied
on. This is what makes me think that it was an intermediate step in
refactoring that shouldn't have ended up in commit history.
* demo kwarg with none(false)
* Reorder and extend tests for arg::none(false) in test_methods_and_attributes.py::test_accepts_none
* Fix arg::none() for keyword arguments
* Add changelog note
* Fix names of no_none_kw test functions
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
* Demonstrate test_factory_constructors.py failure without functional changes from #2335
* Revert "Demonstrate test_factory_constructors.py failure without functional changes from #2335"
This reverts commit ca33a8021fc2a3617c3356b188796528f4594419.
* Fix test crash where registered Python type gets garbage collected
* Clean up some more internal structures when class objects go out of scope
* Reduce length of std::erase_if-in-C++20 comment
* Clean up code for cleaning up type internals
* Move cleaning up of type info in internals to tp_dealloc on pybind11_metaclass
* add support for LLVM compiler
* Update include/pybind11/pybind11.h
__forced_unwind libc++ vs libstdc++
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
* Deprecated public constructors of module
* Turn documentation comment of module_::add_object into valid doxygen documentation
* Move definition of PYBIND11_DETAIL_MODULE_STATIC_DEF and PYBIND11_DETAIL_MODULE_CREATE macros up
* Move detail::create_top_level_module to module_::create_extension_module, and unify Python 2 and 3 signature again
* Throw error_already_set if module creation fails in module_::create_extension_module
* Mention module_::create_extension_module in deprecation warning message of module_::module_
* Check scope's __dict__ instead of using hasattr when registering classes and exceptions, to allow registering the same name in a derived class scope
* Extend test_base_and_derived_nested_scope test
* Add tests on error being thrown registering duplicate classes
* Circumvent bug with combination of test_class.py::test_register_duplicate_class and test_factory_constructors.py::test_init_factory_alias
* fix: PYBIND11_OBJECT could only be used inside the pybind11 namespace (regression)
* docs: add changelog for conversion protection change
* ci: update to Python 3.9
* Fail on passing py::object with wrong Python type to py::object subclass using PYBIND11_OBJECT macro
* Split off test_non_converting_constructors from test_constructors
* Fix test_as_type, as py::type constructor now throws an error itself if the argument is not a type
* Replace tp_name access by pybind11::detail::get_fully_qualified_tp_name
* Move forward-declaration of get_fully_qualified_tp_name to detail/common.h
* Don't add the builtins module name in get_fully_qualified_tp_name for PyPy
* Add PYBIND11_BUILTINS_MODULE macro, and use it in get_fully_qualified_tp_name
* Remove code inside 'PYPY_VERSION_NUM < 0x06000000' preprocessor if branch
* fix: more cleanup
* Remove more references to PyPy 5.7 and 5.9 in the docs
* Update comment on PyUnicode_UTF* in PyPy
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* tests: New test for ctypes buffers (pybind#2502)
* fix: fix buffer_info segfault on views with no stride (pybind11#2502)
* Explicit conversions in buffer_info to make clang happy (pybind#2502)
* Another explicit cast in buffer_info constructor for clang (pybind#2502)
* Simpler implementation of buffer_info constructor from Py_buffer.
* Move test_ctypes_buffer into test_buffers
* Comment on why view->strides may be NULL (and fix some whitespace)
* Use c_strides() instead of zero when view->strides is NULL.
c_strides and f_strides are moved from numpy.h (py::array)
to buffer_info.h (py::detail) so they can be used from the
buffer_info Py_buffer constructor.
* Increase ctypes buffer test coverage in test_buffers.
* Split ctypes tests and skip one which is broken in PyPy2.
* Allow function/functor passed to py::vectorize to return void
* Stealing @sizmailov's test and fixing unused argument warning
* Add missing std::move()
RVO doesn't work here because function return type is different from
actual returned type
* remove extra EOL
* docs: add a few details
* chore: pre-commit autoupdate
* Remove array_iterator, array_begin, and array_end (in detail namespace)
Co-authored-by: Sergei Izmailov <sergei.a.izmailov@gmail.com>
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* Add tests demonstrating the problem with deregistering pybind11 instances
* Fix deregistering of different pybind11 instance from internals
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
Co-authored-by: Blistic <wots_wot@hotmail.com>
* Initializing PyModuleDef object with PyModuleDef_HEAD_INIT.
Python 3.8 documentation: m_base - Always initialize this member to PyModuleDef_HEAD_INIT.
Long-standing (since first github commit in 2015), inconsequential bug.
Also removing inconsequential Py_INCREF(def): PyModule_Create() resets the reference count to 1.
* git rebase master
* moving static PyModuleDef declaration to global scope, as requested by @wjakob
* renaming the two new macros, to start with PYBIND11_DETAIL_MODULE
This changes enum reprs to look like `<Enum.name: value>` similarly to
the Python enum module.
This keeps the str of enums as `Enum.name`, like the Python enum module.
Support C++20. For backwards compatibility, we provide an alias for the old name.
This change is necessary to easily avoid errors when a compiler thinks
`module` is used as a keyword.
* feat: setup.py redesign and helpers
* refactor: simpler design with two outputs
* refactor: helper file update and Windows support
* fix: review points from @YannickJadoul
* refactor: fixes to naming and more docs
* feat: more customization points
* feat: add entry point pybind11-config
* refactor: Try Extension-focused method
* refactor: rename alt/inplace to global
* fix: allow usage with git modules, better docs
* feat: global as an extra (@YannickJadoul's suggestion)
* feat: single version location
* fix: remove the requirement that setuptools must be imported first
* fix: some review points from @wjacob
* fix: use .in, add procedure to docs
* refactor: avoid monkeypatch copy
* docs: minor typos corrected
* fix: minor points from @YannickJadoul
* fix: typo on Windows C++ mode
* fix: MSVC 15 update 3+ have c++14 flag
See <https://docs.microsoft.com/en-us/cpp/build/reference/std-specify-language-standard-version?view=vs-2019>
* docs: discuss making SDists by hand
* ci: use pep517.build instead of manual setup.py
* refactor: more comments from @YannickJadoul
* docs: updates from @ktbarrett
* fix: change to newly recommended tool instead of pep517.build
This was intended as a proof of concept; build seems to be the correct replacement.
See https://github.com/pypa/pep517/pull/83
* docs: updates from @wjakob
* refactor: dual version locations
* docs: typo spotted by @wjakob
* Change base parameter type in register_exception and excepion constructor from PyObject* to handle
* Fix compilation error passing `handle` to `PyObject*`
* Wrap PYBIND11_OVERLOAD_NAME and PYBIND11_OVERLOAD_PURE_NAME in do { ... } while (false), and resolve trailing semicolon
* Deprecate PYBIND11_OVERLOAD_* and get_overload in favor of PYBIND11_OVERRIDE_* and get_override
* Correct erroneous usage of 'overload' instead of 'override' in the implementation and internals
* Fix tests to use non-deprecated PYBIND11_OVERRIDE_* macros
* Update docs to use override instead of overload where appropriate, and add warning about deprecated aliases
* Add semicolons to deprecated PYBIND11_OVERLOAD macros to match original behavior
* Remove deprecation of PYBIND11_OVERLOAD_* macros and get_overload
* Add note to changelog and upgrade guide
* feat: type<T>()
* refactor: using py::type as class
* refactor: py::object as base
* wip: tigher api
* refactor: fix conversion and limit API further
* docs: some added notes from @EricCousineau-TRI
* refactor: use py::type::of
* Added guards to the includes
Added new CI config
Added new trigger
Changed CI workflow name
Debug CI
Debug CI
Debug CI
Debug CI
Added flags fro PGI
Disable Eigen
Removed tests that fail
Uncomment lines
* fix: missing include
fix: minor style cleanup
tests: support skipping
ci: remove and tighten a bit
fix: try msvc workaround for pgic
* tests: split up prealoc tests
* fix: PGI compiler fix
* fix: PGI void_t only
* fix: try to appease nvcc
* ci: better ordering for slow tests
* ci: minor improvements to testing
* ci: Add NumPy to testing
* ci: Eigen generates CUDA warnings / PGI errors
* Added CentOS7 back for a moment
* Fix YAML
* ci: runs-on missing
* centos7 is missing pytest
* ci: use C++11 on CentOS 7
* ci: test something else
* Try just adding flags on CentOS 7
* fix: CentOS 7
* refactor: move include to shared location
* Added verbose flag
* Try to use system cmake3 on CI
* Try to use system cmake3 on CI, attempt2
* Try to use system cmake3 on CI, attempt3
* tests: not finding pytest should be a warning, not a fatal error
* tests: cleanup
* Weird issue?
* fix: final polish
Co-authored-by: Andrii Verbytskyi <andrii.verbytskyi@mpp.mpg.de>
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Andrii Verbytskyi <averbyts@cern.ch>
* Add check if `str(handle)` correctly converted the object, and throw py::error_already_set if not
* Fix tests on Python 3
* Apply @rwgk's fixes to cherry-picked commits from #2392
The variables PYBIND11_HAS_OPTIONAL, PYBIND11_HAS_EXP_OPTIONAL, PYBIND11_HAS_VARIANT,
__clang__, __APPLE__ were not checked for defined in a minortity of instances.
If the project using pybind11 sets -Wundef, the warnings will show.
The test build is also modified to catch the problem.
* fix: support nvcc and test
* fixup! fix: support nvcc and test
* docs: mention what compilers fail
* fix: much simpler logic
* refactor: slightly faster / clearer
Adding missing `bytes` type to `test_constructors()`, to exercise the code change.
The changes in the PR were cherry-picked from PR #2409 (with a very minor
modification in test_pytypes.py related to flake8). Via PR #2409, these
changes were extensively tested in the Google environment, as summarized here:
https://docs.google.com/document/d/1TPL-J__mph_yHa1quDvsO12E_F5OZnvBaZlW9IIrz8M/
The changes in this PR did not cause an issues at all.
Note that `test_constructors()` before this PR passes for Python 2 only
because `pybind11::str` can hold `PyUnicodeObject` or `PyBytesObject`. As a
side-effect of this PR, `test_constructors()` no longer relies on this
permissive `pybind11::str` behavior. However, the permissive behavior is still
exercised/exposed via the existing `test_pybind11_str_raw_str()`.
The test code change is designed to enable easy removal later, when Python 2
support is dropped.
For completeness: confusingly, the non-test code changes travelled through PR
Example `ambiguous conversion` error fixed by this PR:
```
pybind11/tests/test_pytypes.cpp:214:23: error: ambiguous conversion for functional-style cast from 'pybind11::detail::item_accessor' (aka 'accessor<accessor_policies::generic_item>') to 'py::bytes'
"bytes"_a=py::bytes(d["bytes"]),
^~~~~~~~~~~~~~~~~~~~
pybind11/include/pybind11/detail/../pytypes.h:957:21: note: candidate constructor
PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
^
pybind11/include/pybind11/detail/../pytypes.h:957:21: note: candidate constructor
pybind11/include/pybind11/detail/../pytypes.h:987:15: note: candidate constructor
inline bytes::bytes(const pybind11::str &s) {
^
1 error generated.
```
To deal with exceptions that hit destructors or other noexcept functions.
Includes fixes to support Python 2.7 and extends documentation on
error handling.
@virtuald and @YannickJadoul both contributed to this PR.
* Fix warning C26817: Potentially expensive copy of variable 'vh' in range-for loop. Consider making it a const reference (es.71).
* Replace another instance of `for (auto vh : values_and_holders(...))` with `auto vh &` (found by @bstaletic)
Co-authored-by: Michael Goulding <Michael.Goulding@microsoft.com>
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
* Modified Vector STL bind initialization from a buffer type with optimization for simple arrays
* Add subtests to demonstrate processing Python buffer protocol objects with step > 1
* Fixed memoryview step test to only run on Python 3+
* Modified Vector constructor from buffer to return by value for readability
If the default argument value is a class, and not an instance of a
class, `a.value.attr("__repr__")` raises a `ValueError`. Switching to
`repr(a.value)` makes this use case work.
Fixes#2028
* Fix undefined memoryview format
* Add missing <algorithm> header
* Add workaround for py27 array compatibility
* Workaround py27 memoryview behavior
* Fix memoryview constructor from buffer_info
* Workaround PyMemoryView_FromMemory availability in py27
* Fix up memoryview tests
* Update memoryview test from buffer to check signedness
* Use static factory method to create memoryview
* Remove ndim arg from memoryview::frombuffer and add tests
* Allow ndim=0 memoryview and documentation fixup
* Use void* to align to frombuffer method signature
* Add const variants of frombuffer and frommemory
* Add memory view section in doc
* Fix docs
* Add test for null buffer
* Workaround py27 nullptr behavior in test
* Rename frombuffer to from_buffer
This avoids a potential conflict with names in the same scope of the
same name as the embedded module, like namespaces or other global
variables.
Fixes#2172
* Change NAMESPACE_BEGIN and NAMESPACE_END macros into PYBIND11_NAMESPACE_BEGIN and PYBIND11_NAMESPACE_END
* Fix sudden HomeBrew 'python not installed' error
* Sweep difference in 'Class.__init__() must be called when overriding __init__' error message between CPython and PyPy under the rug
* Homebrew updated to 3.8 yesterday.
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
* Error out eval_file
* Enable dynamic attribute support for Pypy >= 6
* Add a test for dynamic attribute support
* Skip test for eval_file on pypy
* Workaround for __qualname__ on PyPy3
* Add a PyPy3.6 7.3.0 build
* Only disable in PyPy3
* Fix travis testing
* No numpy and scipy for pypy
* Enable test on pypy2
* Fix logic in eval_file
* Skip a few tests due to bugs in PyPy
* scipy wheels are broken. make pypy2 a failrue
Co-authored-by: Andreas Kloeckner <inform@tiker.net>
The PyEval_InitThreads() and PyEval_ThreadsInitialized() functions are
now deprecated and will be removed in Python 3.11. Calling
PyEval_InitThreads() now does nothing. The GIL is initialized by
Py_Initialize() since Python 3.7.
For rationale, see #2241, eeb1044818af5b70761deae602c49eba439164dc;
there is a second entry point function defined by the PYBIND11_MODULE
macro that also needs to be annotated as unused.
This change defines a new, portable macro PYBIND11_MAYBE_UNUSED to
mark declarations as unused, and annotates the PYBIND11_MODULE entry
point with this attribute.
The purpose of this annotation is to facilitate dead code detection,
which might otherwise consider the module entry point function dead,
since it isn't otherwise used. (It is only used via FFI.)
This adds support for a `py::args_kw_only()` annotation that can be
specified between `py::arg` annotations to indicate that any following
arguments are keyword-only. This allows you to write:
m.def("f", [](int a, int b) { /* ... */ },
py::arg("a"), py::args_kw_only(), py::arg("b"));
and have it work like Python 3's:
def f(a, *, b):
# ...
with respect to how `a` and `b` arguments are accepted (that is, `a` can
be positional or by keyword; `b` can only be specified by keyword).
Currently user specializations of the form
template <typename itype> struct polymorphic_type_hook<itype, std::enable_if_t<...>> { ... };
will fail if itype is also polymorphic, because the existing specialization will also
be enabled, which leads to 2 equally viable candidates. With this change, user provided
specializations have higher priority than the built in specialization for polymorphic types.
When binding code immediately throws an exception of type
py::error_already_set (e.g. via py::module::import that fails), the
catch block sets an import error as expected. Unfortunately, following
this, the deconstructor of py::error_already_set decides to call
py::detail::get_internals() and set up various internal data structures
of pybind11, which fails given that the error flag is active. The call
stack of this looks as follows:
Py_init_mymodule() -> __cxa_decrement_exception_refcount ->
error_already_set::~error_already_set() ->
gil_scoped_acquire::gil_scoped_acquire() -> detail::get_internals() ->
... -> pybind11::detail::simple_collector() -> uh oh..
The solution is simple: we call detail::get_internals() once before
running any binding code to make sure that the internal data structures
are ready.
This commit introduces the use of C++17-style fold expressions when
casting tuples & the argument lists of functions.
This change can improve performance of the resulting bindings: because
fold expressions have short-circuiting semantics, pybind11 e.g. won't
try to cast the second argument of a function if the first one failed.
This is particularly effective when working with functions that have
many overloads with long argument lists.
* test pair-copyability on C++17 upwards
The stdlib falsely detects containers like M=std::map<T, U>
as copyable, even when one of T and U is not copyable.
Therefore we cannot rely on the stdlib dismissing std::pair<T, M>
by itself, even on C++17.
* fix is_copy_assignable
bind_map used std::is_copy_assignable which suffers from the same problems
as std::is_copy_constructible, therefore the same fix has been applied.
* created tests for copyability
Don't assume that just because the language version is C++17 that the
standard library offers all C++17 features, too. When using clang-6.0
and --std=c++17 on Ubuntu 18.04 with libstdc++, __cpp_sized_deallocation
is false.
When building with `-Werror,-Wmissing-prototypes`, `clang` complains about missing prototypes for functions defined through macro expansions. This PR adds the missing prototypes.
```
error: no previous prototype for function 'pybind11_init_impl_embedded' [
-Werror,-Wmissing-prototypes]
PYBIND11_EMBEDDED_MODULE(embedded, mod) {
^
external/pybind11/include/pybind11/embed.h:61:5: note: expanded from macro 'PYBIND11_EMBEDDED_MODULE'
PYBIND11_EMBEDDED_MODULE_IMPL(name) \
^
external/pybind11/include/pybind11/embed.h:26:23: note: expanded from macro 'PYBIND11_EMBEDDED_MODULE_IMPL'
extern "C" void pybind11_init_impl_##name() { \
^
<scratch space>:380:1: note: expanded from here
pybind11_init_impl_embedded
^
1 error generated.
```
* Adapt to python3.8 C API change
Do `Py_DECREF(type)` on all python objects on deallocation
fix#1946
* Add bare python3.8 build to CI matrix
While numpy/scipy wheels are available, run python3.8 test without them
* fix: Avoid conversion to `int_` rhs argument of enum eq/ne
* test: compare unscoped enum with strings
* suppress comparison to None warning
* test unscoped enum arithmetic and comparision with unsupported type
* Make `overload_cast_impl` available in C++11 mode.
Narrow the scope of the `#if defined(PYBIND11_CPP14)` block around overload_cast to only
cover the parts where C++14 is stricly required. Thus, the implementation in
`pybind11::details::overload_cast_impl` is still available in C++11 mode.
* PR #1581: Modify test to use overload_cast_impl, update docs and change log
The -Wmissing-prototypes Clang warning (or -Wmissing-declarations on
GCC) is very useful to avoid accidents where a function definition in a
source file doesn't match the corresponding declaration in a header
file, as it would warn already during compilation and not much later
during link time.
Unfortunately this means that exported functions defined only in the
source file (usually the ones annotated with `extern "C"`) will cause
this warning to be emitted too (on Clang, GCC has a slightly different
behavior with -Wmissing-declarations and doesn't warn here). This fixes
the warning by providing a declaration right before the definition.
Clang has a bug [1] in x86 Windows that is exposed by the use of lambdas with "unforwardable" prototypes. The error is "error: cannot compile this forwarded non-trivially copyable parameter yet", and the message was introduced in [2] (used to be an assertion).
[1] https://llvm.org/bugs/show_bug.cgi?id=28299
[2] feb1567e07
This is only necessary if `get_internals` is called for the first time in a given module when the running thread is in a GIL-released state.
Fixes#1364
* Test dtype field order in numpy dtype tests
When running tests with NumPy 1.14 or later this test exposes the
"invalid buffer descriptor" error reported in #1274.
* Create dtype_ptr with ordered fields
* Fix casting of time points with non-system-clock duration on Windows
Add explicit `time_point_cast` to time point with duration of system
clock. Fixes Visual Studio compile error.
* Add test case for custom time points casting
In def_readonly and def_readwrite, there is an assertion that the member comes
from the class or a base class:
static_assert(std::is_base_of<C, type>::value, "...");
However, if C and type are the same type, is_base_of will still only be true
if they are the same _non-union_ type. This means we can't define accessors
for the members of a union type because of this assertion.
Update the assertion to test
std::is_same<C, type>::value || std::is_base_of<C, type>::value
which will allow union types, or members of base classes.
Also add a basic unit test for accessing unions.
* Fix async Python functors invoking from multiple C++ threads (#1587)
Ensure GIL is held during functor destruction.
* Add async Python callbacks test that runs in separate Python thread
In some cases the user of pythonbuf needs to allocate the internal
buffer to a specific size e.g. for performance or to enable synchronous
writes to the buffer.
By changing `pythonbuf::d_buffer` to be dynamically allocated we can now
enable these use-cases while still providing the default behavior of
allocating a 1024 byte internal buffer (through a default parameter).
Bazel has a "strict" build model that requires all C++ header files be compilable on their own, and thus must explicitly #include all headers they require (even if de facto header inclusion order means they'd get them "for free"). This adds a couple of headers that are needed (but missing) by this model.
* Fixing order of arguments in call to PyErr_GivenExceptionMatches in pybind11::error_already_set.matches
* Added tests on error_already_set::matches fix for exception base classes
* Fix warning that not including a cmake source or build dir will be a fatal error (it is now on newest CMakes)
* Fixes appveyor
* Travis uses CMake 3.9 for more than a year now
* Travis dropped sudo: false in December
* Dropping Sphinx 2
- clang7: Suppress self-assign warnings; fix missing virtual dtors
- pypy:
- Keep old version (newer stuff breaks)
- Pin packages to extra index for speed
- travis:
- Make docker explicit; remove docker if not needed
- Make commands more verbose (for debugging / repro)
- Make Ubuntu dist explicit per job
- Fix Windows
- Add names to travis
This avoids GIL deadlocking when pybind11 tries to acquire the GIL in a thread that already acquired it using standard Python API (e.g. when running from a Python thread).
* Adds std::deque to the types supported by list_caster in stl.h.
* Adds a new test_deque test in test_stl.{py,cpp}.
* Updates the documentation to include std::deque as a default
supported type.
* Check default holder
-Recognize "std::unique_ptr<T, D>" as a default holder even if "D" doesn't match between base and derived holders
* Add test for unique_ptr<T, D> change
Pybind11 provides a cast operator between opaque void* pointers on the
C++ side and capsules on the Python side. The py::cast<void *>
expression was not aware of this possibility and incorrectly triggered a
compile-time assertion ("Unable to cast type to reference: value is
local to type caster") that is now fixed.
* Support C++17 aligned new statement
This patch makes pybind11 aware of nonstandard alignment requirements in
bound types and passes on this information to C++17 aligned 'new'
operator. Pre-C++17, the behavior is unchanged.
This PR brings the std::array<> caster in sync with the other STL type
casters: to accept an arbitrary sequence as input (rather than a list,
which is too restrictive).
* Fix for Issue #1258
list_caster::load method will now check for a Python string and prevent its automatic conversion to a list.
This should fix the issue "pybind11/stl.h converts string to vector<string> #1258" (https://github.com/pybind/pybind11/issues/1258)
* Added tests for fix of issue #1258
* Changelog: stl string auto-conversion
* Fix potential crash when calling an overloaded function
The crash would occur if:
- dispatcher() uses two-pass logic (because the target is overloaded and some arguments support conversions)
- the first pass (with conversions disabled) doesn't find any matching overload
- the second pass does find a matching overload, but its return value can't be converted to Python
The code for formatting the error message assumed `it` still pointed to the selected overload,
but during the second-pass loop `it` was nullptr. Fix by setting `it` correctly if a second-pass
call returns a nullptr `handle`. Add a new test that segfaults without this fix.
* Make overload iteration const-correct so we don't have to iterate again on second-pass error
* Change test_error_after_conversions dependencies to local classes/variables
This commit addresses an inefficiency in how enums are created in
pybind11. Most of the enum_<> implementation is completely generic --
however, being a template class, it ended up instantiating vast amounts
of essentially identical code in larger projects with many enums.
This commit introduces a generic non-templated helper class that is
compatible with any kind of enumeration. enum_ then becomes a thin
wrapper around this new class.
The new enum_<> API is designed to be 100% compatible with the old one.
object_api::operator[] has a powerful overload for py::handle that can
accept slices, tuples (for NumPy), etc.
Lists, sequences, and tuples provide their own specialized operator[],
which unfortunately disables this functionality. This is accidental, and
the purpose of this commit is to re-enable the more general behavior.
This commit is tangentially related to the previous one in that it makes
py::handle/py::object et al. behave more like their Python counterparts.
This commit revamps the object_api class so that it maps most C++
operators to their Python analogs. This makes it possible to, e.g.
perform arithmetic using a py::int_ or py::array.
* check for already existing enum value added; added test
* added enum value name to exception message
* test for defining enum with multiple identical names moved to test_enum.cpp/py
This PR adds a new py::ellipsis() method which can be used in
conjunction with NumPy's generalized slicing support. For instance,
the following is now valid (where "a" is a NumPy array):
py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];
* stl.h: propagate return value policies to type-specific casters
Return value policies for containers like those handled in in 'stl.h'
are currently broken.
The problem is that detail::return_value_policy_override<C>::policy()
always returns 'move' when given a non-pointer/reference type, e.g.
'std::vector<...>'.
This is sensible behavior for custom types that are exposed via
'py::class_<>', but it does not make sense for types that are handled by
other type casters (STL containers, Eigen matrices, etc.).
This commit changes the behavior so that
detail::return_value_policy_override only becomes active when the type
caster derives from type_caster_generic.
Furthermore, the override logic is called recursively in STL type
casters to enable key/value-specific behavior.
* Switching deprecated Thread Local Storage (TLS) usage in Python 3.7 to Thread Specific Storage (TSS)
* Changing Python version from 3.6 to 3.7 for Travis CI, to match brew's version of Python 3
* Introducing PYBIND11_ macros to switch between TLS and TSS API
The current code requires implicitly that integral types are cast-able to floating point. In case of strongly-typed integrals (e.g. as explained at http://www.ilikebigbits.com/blog/2014/5/6/type-safe-identifiers-in-c) this is not always the case.
This commit uses SFINAE to move the numeric conversions into separate `cast()` implementations to avoid the issue.
If an exception is thrown during module initialization, the
error_already_set destructor will try to call `get_internals()` *after*
setting Python's error indicator, resulting in a `SystemError: ...
returned with an error set`.
Fix that by temporarily stashing away the error indicator in the
destructor.
When using pybind11 to bind enums on MSVC and warnings (/W4) enabled,
the following warning pollutes builds. This fix renames one of the
occurrences.
pybind11\include\pybind11\pybind11.h(1398): warning C4459: declaration of 'self' hides global declaration
pybind11\include\pybind11\operators.h(41): note: see declaration of 'pybind11::detail::self'
* Add basic support for tag-based static polymorphism
Sometimes it is possible to look at a C++ object and know what its dynamic type is,
even if it doesn't use C++ polymorphism, because instances of the object and its
subclasses conform to some other mechanism for being self-describing; for example,
perhaps there's an enumerated "tag" or "kind" member in the base class that's always
set to an indication of the correct type. This might be done for performance reasons,
or to permit most-derived types to be trivially copyable. One of the most widely-known
examples is in LLVM: https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html
This PR permits pybind11 to be informed of such conventions via a new specializable
detail::polymorphic_type_hook<> template, which generalizes the previous logic for
determining the runtime type of an object based on C++ RTTI. Implementors provide
a way to map from a base class object to a const std::type_info* for the dynamic
type; pybind11 then uses this to ensure that casting a Base* to Python creates a
Python object that knows it's wrapping the appropriate sort of Derived.
There are a number of restrictions with this tag-based static polymorphism support
compared to pybind11's existing support for built-in C++ polymorphism:
- there is no support for this-pointer adjustment, so only single inheritance is permitted
- there is no way to make C++ code call new Python-provided subclasses
- when binding C++ classes that redefine a method in a subclass, the .def() must be
repeated in the binding for Python to know about the update
But these are not much of an issue in practice in many cases, the impact on the
complexity of pybind11's innards is minimal and localized, and the support for
automatic downcasting improves usability a great deal.
The property returns the enum_ value as a string.
For example:
>>> import module
>>> module.enum.VALUE
enum.VALUE
>>> str(module.enum.VALUE)
'enum.VALUE'
>>> module.enum.VALUE.name
'VALUE'
This is actually the equivalent of Boost.Python "name" property.
As reported in #1349, clang before 3.5 can segfault on a function-local
variable referenced inside a lambda. This moves the function-local
static into a separate function that the lambda can invoke to avoid the
issue.
Fixes#1349
This reimplements the version check to avoid sscanf (which has
reportedly started throwing warnings under MSVC, even when used
perfectly safely -- #1314). It also extracts the mostly duplicated
parts of PYBIND11_MODULE/PYBIND11_PLUGIN into separate macros.
- PYBIND11_MAKE_OPAQUE now takes ... rather than a single argument and
expands it with __VA_ARGS__; this lets templated, comma-containing
types get through correctly.
- Adds a new macro PYBIND11_TYPE() that lets you pass the type into a
macro as a single argument, such as:
PYBIND11_OVERLOAD(PYBIND11_TYPE(R<1,2>), PYBIND11_TYPE(C<3,4>), func)
Unfortunately this only works for one macro call: to forward the
argument on to the next macro call (without the processor breaking it
up again) requires also adding the PYBIND11_TYPE(...) to type macro
arguments in the PYBIND11_OVERLOAD_... macro chain.
- updated the documentation with these two changes, and use them at a couple
places in the test suite to test that they work.
This updates the `py::init` constructors to only use brace
initialization for aggregate initiailization if there is no constructor
with the given arguments.
This, in particular, fixes the regression in #1247 where the presence of
a `std::initializer_list<T>` constructor started being invoked for
constructor invocations in 2.2 even when there was a specific
constructor of the desired type.
The added test case demonstrates: without this change, it fails to
compile because the `.def(py::init<std::vector<int>>())` constructor
tries to invoke the `T(std::initializer_list<std::vector<int>>)`
constructor rather than the `T(std::vector<int>)` constructor.
By only using `new T{...}`-style construction when a `T(...)`
constructor doesn't exist, we should bypass this by while still allowing
`py::init<...>` to be used for aggregate type initialization (since such
types, by definition, don't have a user-declared constructor).
* Fix segfault when reloading interpreter with external modules
When embedding the interpreter and loading external modules in that
embedded interpreter, the external module correctly shares its
internals_ptr with the one in the embedded interpreter. When the
interpreter is shut down, however, only the `internals_ptr` local to
the embedded code is actually reset to nullptr: the external module
remains set.
The result is that loading an external pybind11 module, letting the
interpreter go through a finalize/initialize, then attempting to use
something in the external module fails because this external module is
still trying to use the old (destroyed) internals. This causes
undefined behaviour (typically a segfault).
This commit fixes it by adding a level of indirection in the internals
path, converting the local internals variable to `internals **` instead
of `internals *`. With this change, we can detect a stale internals
pointer and reload the internals pointer (either from a capsule or by
creating a new internals instance).
(No issue number: this was reported on gitter by @henryiii and @aoloe).
The anonymous struct nested in a union triggers a -Wnested-anon-type
warning ("anonymous types declared in an anonymous union are an
extension") under clang (#1204). This names the struct and defines it
out of the definition of `instance` to get around to warning (and makes
the code slightly simpler).
PEP8 indicates (correctly, IMO) that when an annotation is present, the
signature should include spaces around the equal sign, i.e.
def f(x: int = 1): ...
instead of
def f(x: int=1): ...
(in the latter case the equal appears to bind to the type, not to the
argument).
pybind11 signatures always includes a type annotation so we can always
add the spaces.
When using the mixed position + vararg path, pybind over inc_ref's
the vararg positions. Printing the ref_count() of `item` before
and after this change you see:
Before change:
```
refcount of item before assign 3
refcount of item after assign 5
```
After change
```
refcount of item before assign 3
refcount of item after assign 4
```
The `py::args` or `py::kwargs` arguments aren't properly referenced
when added to the function_call arguments list: their reference counts
drop to zero if the first (non-converting) function call fails, which
means they might be cleaned up before the second pass call runs.
This commit adds a couple of extra `object`s to the `function_call`
where we can stash a reference to them when needed to tie their
lifetime to the function_call object's lifetime.
(Credit to YannickJadoul for catching and proposing a fix in #1223).
In the latest MSVC in C++17 mode including Eigen causes warnings:
warning C4996: 'std::unary_negate<_Fn>': warning STL4008: std::not1(),
std::not2(), std::unary_negate, and std::binary_negate are deprecated in
C++17. They are superseded by std::not_fn(). You can define
_SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING or
_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have
received this warning.
This disables 4996 for the Eigen includes.
Catch generates a similar warning for std::uncaught_exception, so
disable the warning there, too.
In both cases this is temporary; we can (and should) remove the warnings
disabling once new upstream versions of Eigen and Catch are available
that address the warning. (The Catch one, in particular, looks to be
fixed in upstream master, so will probably be fixed in the next (2.0.2)
release).
Pybind11's default conversion to int always produces a long on Python 2 (`int`s and `long`s were unified in Python 3). This patch fixes `int` handling to match Python 2 on Python 2; for short types (`size_t` or smaller), the number will be returned as an `int` if possible, otherwise `long`. Requires Python 2.5+.
This is needed for things like `sys.exit`, which refuse to accept a `long`.
This commit turns on `-Wdeprecated` in the test suite and fixes several
associated deprecation warnings that show up as a result:
- in C++17 `static constexpr` members are implicitly inline; our
redeclaration (needed for C++11/14) is deprecated in C++17.
- various test suite classes have destructors and rely on implicit copy
constructors, but implicit copy constructor definitions when a
user-declared destructor is present was deprecated in C++11.
- Eigen also has various implicit copy constructors, so just disable
`-Wdeprecated` in `eigen.h`.
py::class_<T>'s `def_property` and `def_property_static` can now take a
`nullptr` as the getter to allow a write-only property to be established
(mirroring Python's `property()` built-in when `None` is given for the
getter).
This also updates properties to use the new nullptr constructor internally.
A few fixes related to how we set `__qualname__` and how we show the
type name in function signatures:
- `__qualname__` isn't supposed to have the module name at the
beginning, but we've been putting it there. This removes it, while
keeping the `Nested.Class` name chaining.
- print `__module__.__qualname__` rather than `type->tp_name`; the
latter doesn't work properly for nested classes, so we would get
`module.B` rather than `module.A.B` for a class `B` with parent `A`.
This also unifies the Python 3 and PyPy code. Fixes#1166.
- This now sets a `__qualname__` attribute on the type (as would happen
in Python 3.3+) for Python <3.3, including PyPy. While not particularly
important to have in earlier Python versions, it's useful for us to be
able to extracted the nested name, which is why `__qualname__` was
invented in the first place.
- Added tests for the above.
Building with the (VS2017) /permissive- flag puts the compiler into
stricter standards-compliant mode. It shouldn't cause the compiler to
work differently--it just disallows some non-conforming code--so should
be perfectly fine for the test suite under all VS2017 builds.
This commit also fixes one failure under non-permissive mode.
This fixes a bug introduced in b68959e822
when passing in a two-dimensional, but conformable, array as the value
for a compile-time Eigen vector (such as VectorXd or RowVectorXd). The
commit switched to using numpy to copy into the eigen data, but this
broke the described case because numpy refuses to broadcast a (N,1)
into a (N).
This commit fixes it by squeezing the input array whenever the output
array is 1-dimensional, which will let the problematic case through.
(This shouldn't squeeze inappropriately as dimension compatibility is
already checked for conformability before getting to the copy code).
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
This changes the caster to return a reference to a (new) local `CharT`
type caster member so that binding lvalue-reference char arguments
works (currently it results in a compilation failure).
Fixes#1116
`type_descr` is now applied only to the final signature so that it only
marks the argument types, but not nested types (e.g. for tuples) or
return types.
MSCV does not allow `&typeid(T)` in constexpr contexts, but the string
part of the type signature can still be constexpr. In order to avoid
`typeid` as long as possible, `descr` is modified to collect type
information as template parameters instead of constexpr `typeid`.
The actual `std::type_info` pointers are only collected in the end,
as a `constexpr` (gcc/clang) or regular (MSVC) function call.
Not only does it significantly reduce binary size on MSVC, gcc/clang
benefit a little bit as well, since they can skip some intermediate
`std::type_info*` arrays.
The current C++14 constexpr signatures don't require relaxed constexpr,
but only `auto` return type deduction. To get around this in C++11,
the type caster's `name()` static member functions are turned into
`static constexpr auto` variables.
E.g. trying to convert a `list` to a `std::vector<int>` without
including <pybind11/stl.h> will now raise an error with a note that
suggests checking the headers.
The note is only appended if `std::` is found in the function
signature. This should only be the case when a header is missing.
E.g. when stl.h is included, the signature would contain `List[int]`
instead of `std::vector<int>` while using stl_bind.h would produce
something like `MyVector`. Similarly for `std::map`/`Dict`, `complex`,
`std::function`/`Callable`, etc.
There's a possibility for false positives, but it's pretty low.
To avoid an ODR violation in the test suite while testing
both `stl.h` and `std_bind.h` with `std::vector<bool>`,
the `py::bind_vector<std::vector<bool>>` test is moved to
the secondary module (which does not include `stl.h`).
There are two separate additions:
1. `py::hash(obj)` is equivalent to the Python `hash(obj)`.
2. `.def(hash(py::self))` registers the hash function defined by
`std::hash<T>` as the Python hash function.
The lookup of the `self` type and value pointer are moved out of
template code and into `dispatcher`. This brings down the binary
size of constructors back to the level of the old placement-new
approach. (It also avoids a second lookup for `init_instance`.)
With this implementation, mixing old- and new-style constructors
in the same overload set may result in some runtime overhead for
temporary allocations/deallocations, but this should be fine as
old style constructors are phased out.
Creating an instance of of a pybind11-bound type caused a reference leak in the
associated Python type object, which could prevent these from being collected
upon interpreter shutdown. This commit fixes that issue for all types that are
defined in a scope (e.g. a module). Unscoped anonymous types (e.g. custom
iterator types) always retain a positive reference count to prevent their
collection.
The current PYBIND11_INTERNALS_ID depends on the version of the library
in order to isolate binary incompatible internals capsules. However,
this does not preclude conflicts between modules built from different
(binary incompatible) commits with the same version number.
For example, if one module was built with an early v2.2.dev and
submitted to PyPI, it could not be loaded alongside a v2.2.x release
module -- it would segfault because of incompatible internals with
the same ID.
This PR changes the ID to depend on PYBIND11_INTERNALS_VERSION which is
independent of the main library version. It's an integer which should be
incremented whenever a binary incompatible change is made to internals.
PYBIND11_INTERNALS_KIND is also introduced for a similar reason.
The same versioning scheme is also applied to `type_info` and the
`module_local` type attribute.
The "see above" comment being referenced in the code comments isn't
"above" anymore; copy the later factory init comment into the first
constructor block to fix it.
The main point of `py::module_local` is to make the C++ -> Python cast
unique so that returning/casting a C++ instance is well-defined.
Unfortunately it also makes loading unique, but this isn't particularly
desirable: when an instance contains `Type` instance there's no reason
it shouldn't be possible to pass that instance to a bound function
taking a `Type` parameter, even if that function is in another module.
This commit solves the issue by allowing foreign module (and global)
type loaders have a chance to load the value if the local module loader
fails. The implementation here does this by storing a module-local
loading function in a capsule in the python type, which we can then call
if the local (and possibly global, if the local type is masking a global
type) version doesn't work.
This reimplements the py::init<...> implementations using the various
functions added to support `py::init(...)`, and moves the implementing
structs into `detail/init.h` from `pybind11.h`. It doesn't simply use a
factory directly, as this is a very common case and implementation
without an extra lambda call is a small but useful optimization.
This, combined with the previous lazy initialization, also avoids
needing placement new for `py::init<...>()` construction: such
construction now occurs via an ordinary `new Type(...)`.
A consequence of this is that it also fixes a potential bug when using
multiple inheritance from Python: it was very easy to write classes
that double-initialize an existing instance which had the potential to
leak for non-pod classes. With the new implementation, an attempt to
call `__init__` on an already-initialized object is now ignored. (This
was already done in the previous commit for factory constructors).
This change exposed a few warnings (fixed here) from deleting a pointer
to a base class with virtual functions but without a virtual destructor.
These look like legitimate warnings that we shouldn't suppress; this
adds virtual destructors to the appropriate classes.
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.
An alias can be used for two main purposes: to override virtual methods,
and to add some extra data to a class needed for the pybind-wrapper.
Both of these absolutely require that the wrapped class be polymorphic
so that virtual dispatch and destruction, respectively, works.
`function_signature_t` extracts the function type from a function,
function pointer, or lambda.
`is_lambda` (which is really
`is_not_a_function_or_pointer_or_member_pointer`, but that name is a
bit too long) checks whether the type is (in the approprate context) a
lambda.
`is_function_pointer` checks whether the type is a pointer to a
function.
We currently allocate instance values when creating the instance itself
(except when constructing the instance for a `cast()`), but there is no
particular reason to do so: the instance itself and the internals (for
a non-simple layout) are allocated via Python, with no reason to
expect better locality from the invoked `operator new`. Moreover, it
makes implementation of factory function constructors trickier and
slightly less efficient: they don't use the pre-eallocate the memory,
which means there is a pointless allocation and free.
This commit makes the allocation lazy: instead of preallocating when
creating the instance, the allocation happens when the instance is
first loaded (if null at that time).
In addition to making it more efficient to deal with cases that don't
need preallocation, this also allows for a very slight performance
increase by not needing to look up the instances types during
allocation. (There is a lookup during the eventual load, of course, but
that is happening already).
This adds a PYBIND11_NAMESPACE macro that expands to the `pybind11`
namespace with hidden visibility under gcc-type compilers, and otherwise
to the plain `pybind11`. This then forces hidden visibility on
everything in pybind, solving the visibility issues discussed at end
end of #949.
In C++11 mode, `boost::apply_visitor` requires an explicit `result_type`.
This also adds optional tests for `boost::variant` in C++11/14, if boost
is available. In C++17 mode, `std::variant` is tested instead.
The current `py::overload_cast` is hitting some ICEs under both MSVC
2015 and clang 3.8 on debian with the rewritten test suites; adding an
empty constexpr constructor to the `overload_cast_impl` class seems to
avoid the ICE.
Attempting to mix py::module_local and non-module_local classes results
in some unexpected/undesirable behaviour:
- if a class is registered non-local by some other module, a later
attempt to register it locally fails. It doesn't need to: it is
perfectly acceptable for the local registration to simply override
the external global registration.
- going the other way (i.e. module `A` registers a type `T` locally,
then `B` registers the same type `T` globally) causes a more serious
issue: `A.T`'s constructors no longer work because the `self` argument
gets converted to a `B.T`, which then fails to resolve.
Changing the cast precedence to prefer local over global fixes this and
makes it work more consistently, regardless of module load order.
Types need `tp_name` set to a C-style string, but the current `strdup`
ends up with a leak (issue #977). This avoids the strdup by storing
the `std::string` in internals so that during interpreter shutdown it
will be properly destroyed.
This commit adds a `py::module_local` attribute that lets you confine a
registered type to the module (more technically, the shared object) in
which it is defined, by registering it with:
py::class_<C>(m, "C", py::module_local())
This will allow the same C++ class `C` to be registered in different
modules with independent sets of class definitions. On the Python side,
two such types will be completely distinct; on the C++ side, the C++
type resolves to a different Python type in each module.
This applies `py::module_local` automatically to `stl_bind.h` bindings
when the container value type looks like something global: i.e. when it
is a converting type (for example, when binding a `std::vector<int>`),
or when it is a registered type itself bound with `py::module_local`.
This should help resolve potential future conflicts (e.g. if two
completely unrelated modules both try to bind a `std::vector<int>`.
Users can override the automatic selection by adding a
`py::module_local()` or `py::module_local(false)`.
Note that this does mildly break backwards compatibility: bound stl
containers of basic types like `std::vector<int>` cannot be bound in one
module and returned in a different module. (This can be re-enabled with
`py::module_local(false)` as described above, but with the potential for
eventual load conflicts).
The builtin exception handler currently doesn't work across modules
under clang/libc++ for builtin pybind exceptions like
`pybind11::error_already_set` or `pybind11::stop_iteration`: under
RTLD_LOCAL module loading clang considers each module's exception
classes distinct types. This then means that the base exception
translator fails to catch the exceptions and the fall through to the
generic `std::exception` handler, which completely breaks things like
`stop_iteration`: only the `stop_iteration` of the first module loaded
actually works properly; later modules raise a RuntimeError with no
message when trying to invoke their iterators.
For example, two modules defined like this exhibit the behaviour under
clang++/libc++:
z1.cpp:
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
namespace py = pybind11;
PYBIND11_MODULE(z1, m) {
py::bind_vector<std::vector<long>>(m, "IntVector");
}
z2.cpp:
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
namespace py = pybind11;
PYBIND11_MODULE(z2, m) {
py::bind_vector<std::vector<double>>(m, "FloatVector");
}
Python:
import z1, z2
for i in z2.FloatVector():
pass
results in:
Traceback (most recent call last):
File "zs.py", line 2, in <module>
for i in z2.FloatVector():
RuntimeError
This commit fixes the issue by adding a new exception translator each
time the internals pointer is initialized from python builtins: this
generally means the internals data was initialized by some other
module. (The extra translator(s) are skipped under libstdc++).
This commit adds a PYBIND11_UNSHARED_STATIC_LOCALS macro that forces a
function to have hidden visibility under gcc and gcc-compatible
compilers. gcc, in particular, needs this to to avoid sharing static
local variables across modules (which happens even under a RTLD_LOCAL
dlopen()!). clang doesn't appear to have this issue, but the forced
visibility on internal pybind functions certainly won't hurt it and icc.
This updates the workaround from #862 to use this rather than the
version-specific template.
Currently types that are capable of conversion always call their convert
function when invoked with a `py::object` which is actually the correct
type. This means that code such as `py::cast<py::list>(obj)` and
`py::list l(obj.attr("list"))` make copies, which was an oversight
rather than an intentional feature.
While at first glance there might be something behind having
`py::list(obj)` make a copy (as it would in Python), this would be
inconsistent when you dig a little deeper because `py::list(l)`
*doesn't* make a copy for an existing `py::list l`, and having an
inconsistency within C++ would be worse than a C++ <-> Python
inconsistency.
It is possible to get around the copying using a
`reinterpret_borrow<list>(o)` (and this commit fixes one place, in
`embed.h`, that does so), but that seems a misuse of
`reinterpret_borrow`, which is really supposed to be just for dealing
with raw python-returned values, not `py::object`-derived wrappers which
are supposed to be higher level.
This changes the constructor of such converting types (i.e. anything
using PYBIND11_OBJECT_CVT -- `str`, `bool_`, `int_`, `float_`, `tuple`,
`dict`, `list`, `set`, `memoryview`) to reference rather than copy when
the check function passes.
It also adds an `object &&` constructor that is slightly more efficient
by avoiding an inc_ref when the check function passes.
The fix for #960 could result a type being registered multiple times if
its `__init__` is called multiple times. This can happen perfectly
ordinarily when python-side multiple inheritance is involved: for
example, with a diamond inheritance pattern with each intermediate
classes invoking the parent constructor.
With the change in #960, the multiple `__init__` calls meant
`register_instance` was called multiple times, but the deletion only
deleted it once. Thus, if a future instance of the same type was
allocated at the same location, pybind would pick it up as a registered
type.
This fixes the issue by tracking whether a value pointer has been
registered to avoid both double-registering it. (There's also a slight
optimization of not needing to do a registered_instances lookup when the
type is known not registered, but this is secondary).
`error_already_set` is more complicated than it needs to be, partly
because it manages reference counts itself rather than using
`py::object`, and partly because it tries to do more exception clearing
than is needed. This commit greatly simplifies it, and fixes#927.
Using `py::object` instead of `PyObject *` means we can rely on
implicit copy/move constructors.
The current logic did both a `PyErr_Clear` on deletion *and* a
`PyErr_Fetch` on creation. I can't see how the `PyErr_Clear` on
deletion is ever useful: the `Fetch` on creation itself clears the
error, so the only way doing a `PyErr_Clear` on deletion could do
anything if is some *other* exception was raised while the
`error_already_set` object was alive--but in that case, clearing some
other exception seems wrong. (Code that is worried about an exception
handler raising another exception would already catch a second
`error_already_set` from exception code).
The destructor itself called `clear()`, but `clear()` was a little bit
more paranoid that needed: it called `restore()` to restore the
currently captured error, but then immediately cleared it, using the
`PyErr_Restore` to release the references. That's unnecessary: it's
valid for us to release the references manually. This updates the code
to simply release the references on the three objects (preserving the
gil acquire).
`clear()`, however, also had the side effect of clearing the current
error, even if the current `error_already_set` didn't have a current
error (e.g. because of a previous `restore()` or `clear()` call). I
don't really see how clearing the error here can ever actually be
useful: the only way the current error could be set is if you called
`restore()` (in which case the current stored error-related members have
already been released), or if some *other* code raised the error, in
which case `clear()` on *this* object is clearing an error for which it
shouldn't be responsible.
Neither of those seem like intentional or desirable features, and
manually requesting deletion of the stored references similarly seems
pointless, so I've just made `clear()` an empty method and marked it
deprecated.
This also fixes a minor potential issue with the destruction: it is
technically possible for `value` to be null (though this seems likely to
be rare in practice); this updates the check to look at `type` which
will always be non-null for a `Fetch`ed exception.
This also adds error_already_set round-trip throw tests to the test
suite.
The instance registration for offset base types fails (under macOS, with
a segfault) in the presense of virtual base types. The issue occurs
when trying to `static_cast<Base *>(derived_ptr)` when `derived_ptr` has
been allocated (via `operator new`) but not initialized.
This commit fixes the issue by moving the addition to
`registered_instances` into `init_holder` rather than immediately after
value pointer allocation.
This also renames it to `init_instance` since it does more than holder
initialization now. (I also further renamed `init_holder_helper` to
`init_holder` since `init_holder` isn't used anymore).
Fixes#959.
Pre-C++17, std::pair can technically have an copy constructor even
though it can't actually be invoked without a compilation failure (due
to the underlying types being non-copyable). Most stls, including
libc++ since ~3.4, use the C++17 behaviour of not exposing an uncallable
copy constructor, but FreeBSD deliberately broke their libc++ to
preserve the nonsensical behaviour
(https://svnweb.freebsd.org/base?view=revision&revision=261801).
This updates pybind's internal `is_copy_constructible` to also detect
the std::pair case under pre-C++17.
This also everything (except for a couple cases in the internal version)
to use the internal `is_copy_constructible` rather than
`std::is_copy_constructible`.
This adds support for implicit conversions to bool from Python types
with `__bool__` (Python 3) or `__nonzero__` (Python 2) attributes, and
adds direct (i.e. non-converting) support for numpy bools.
If a class doesn't provide a `T::operator delete(void *)` but does have
a `T::operator delete(void *, size_t)` the latter is invoked by a
`delete someT`. Pybind currently only look for and call the former;
this commit adds detection and calling of the latter when the former
doesn't exist.
To fix a difficult-to-reproduce segfault on Python interpreter exit,
ensure that the tp_base field of a handful of new heap-types is
counted as a reference to that base type object.
This changes the pointer `cast()` in `PYBIND11_TYPE_CASTER` to recognize
the `take_ownership` policy: if casting a pointer with take-ownership,
the `cast()` now recalls `cast()` with a dereferenced rvalue (rather
than the previous code, which was always calling it with a const lvalue
reference), and deletes the pointer after the chained `cast()` is
complete.
This makes code like:
m.def("f", []() { return new std::vector<int>(100, 1); },
py::return_value_policy::take_ownership);
do the expected thing by taking over ownership of the returned pointer
(which is deleted once the chained cast completes).
PR #936 broke the ability to return a pointer to a stl container (and,
likewise, to a tuple) because the added deduced type matched a
non-const pointer argument: the pointer-accepting `cast` in
PYBIND11_TYPE_CASTER had a `const type *`, which is a worse match for a
non-const pointer than the universal reference template #936 added.
This changes the provided TYPE_CASTER cast(ptr) to take the pointer by
template arg (so that it will accept either const or non-const pointer).
It has two other effects: it slightly reduces .so size (because many
type casters never actually need the pointer cast at all), and it allows
type casters to provide their untemplated pointer `cast()` that will
take precedence over the templated version provided in the macro.
The value and holder iterator code had a past-the-end iterator
dereference. While of course invalid, the dereference didn't actually
cause any problems (which is why it wasn't caught before) because the
dereferenced value is never actually used and `vector` implementations
appear to allow dereferencing the past-the-end iterator. Under a MSVC
debug build, however, it fails a debug assertion and aborts.
This amends the iterator to just store and use a pointer to the vector
(rather than adding a second past-the-end iterator member), checking the
type index against the type vector size.
ICC was reporting that `try_direct_conversions()` cannot be `constexpr`
because `handle` is not a literal type. The fix removes `constexpr`
from the function since it isn't strictly needed.
This commit also suppresses new false positive warnings which mostly
appear in constexpr contexts (where the compiler knows conversions are
safe).
This updates the std::tuple, std::pair and `stl.h` type casters to
forward their contained value according to whether the container being
cast is an lvalue or rvalue reference. This fixes an issue where
subcaster casts were always called with a const lvalue which meant
nested type casters didn't have the desired `cast()` overload invoked.
For example, this caused Eigen values in a tuple to end up with a
readonly flag (issue #935) and made it impossible to return a container
of move-only types (issue #853).
This fixes both issues by adding templated universal reference `cast()`
methods to the various container types that forward container elements
according to the container reference type.
The std::pair caster can be written as a special case of the std::tuple
caster; this combines them via a base `tuple_caster` class (which is
essentially identical to the previous std::tuple caster).
This also removes the special empty tuple base case: returning an empty
tuple is relatively rare, and the base case still works perfectly well
even when the tuple types is an empty list.
When defining method from a member function pointer (e.g. `.def("f",
&Derived::f)`) we run into a problem if `&Derived::f` is actually
implemented in some base class `Base` when `Base` isn't
pybind-registered.
This happens because the class type is deduced from the member function
pointer, which then becomes a lambda with first argument this deduced
type. For a base class implementation, the deduced type is `Base`, not
`Derived`, and so we generate and registered an overload which takes a
`Base *` as first argument. Trying to call this fails if `Base` isn't
registered (e.g. because it's an implementation detail class that isn't
intended to be exposed to Python) because the type caster for an
unregistered type always fails.
This commit adds a `method_adaptor` function that rebinds a member
function to a derived type member function and otherwise (i.e. regular
functions/lambda) leaves the argument as-is. This is now used for class
definitions so that they are bound with type being registered rather
than a potential base type.
A closely related fix in this commit is to similarly update the lambdas
used for `def_readwrite` (and related) to bind to the class type being
registered rather than the deduced type so that registering a property
that resolves to a base class member similarly generates a usable
function.
Fixes#854, #910.
Co-Authored-By: Dean Moldovan <dean0x7d@gmail.com>
When casting to an unsigned type from a python 2 `int`, we currently
cast using `(unsigned long long) PyLong_AsUnsignedLong(src.ptr())`.
If the Python cast fails, it returns (unsigned long) -1, but then we
cast this to `unsigned long long`, which means we get 4294967295, but
because that isn't equal to `(unsigned long long) -1`, we don't detect
the failure.
This commit moves the unsigned casting into a `detail::as_unsigned`
function which, upon error, casts -1 to the final type, and otherwise
casts the return value to the final type to avoid the problematic double
cast when an error occurs.
The error most commonly shows up wherever `long` is 32-bits (e.g. under
both 32- and 64-bit Windows, and under 32-bit linux) when passing a
negative value to a bound function taking an `unsigned long`.
Fixes#929.
The added tests also trigger a latent segfault under PyPy: when casting
to an integer smaller than `long` (e.g. casting to a `uint32_t` on a
64-bit `long` architecture) we check both for a Python error and also
that the resulting intermediate value will fit in the final type. If
there is no conversion error, but we get a value that would overflow, we
end up calling `PyErr_ExceptionMatches()` illegally: that call is only
allowed when there is a current exception. Under PyPy, this segfaults
the test suite. It doesn't appear to segfault under CPython, but the
documentation suggests that it *could* do so. The fix is to only check
for the exception match if we actually got an error.
This fixes#856. Instead of the weakref trick, the internals structure
holds an unordered_map from PyObject* to a vector of references. To
avoid the cost of the unordered_map lookup for objects that don't have
any keep_alive patients, a flag is added to each instance to indicate
whether there is anything to do.
Using `std::type_info::operator==` fails under libc++ because the .so
is loaded with RTLD_LOCAL. libc++ considers types under such .sos
distinct, and so comparing typeid() values directly isn't going to work.
This adds a custom hasher and equality class for the type lookup maps
when not under stdlibc++, and adds a `detail::same_type` function to
perform the equality test. It also converts a few pointer arguments to
const lvalue references, particularly since doing the pointer
comparison wasn't technically valid to being with (though in practice,
appeared to work everywhere).
This fixes#912.
Fixes a race condition when multiple threads try to acquire the GIL
before `detail::internals` have been initialized. `gil_scoped_release`
is now tasked with initializing `internals` (guaranteed single-threaded)
to ensure the safety of subsequent `acquire` calls from multiple threads.
Fixes the issue as described in the comments of commit e27ea47. This
just adds `enable_if_t<std::is_move_constructible<T>::value>` to
`make_move_constructor`. The change fixes MSVC and is harmless with
other compilers.
CLion slows to a crawl when evaluating the intricate `PYBIND11_NUMPY_DTYPE`
macro. This commit replaces the macro cascade with a simple `(void)0`
to ease IDE evaluation.
This commit allows multiple inheritance of pybind11 classes from
Python, e.g.
class MyType(Base1, Base2):
def __init__(self):
Base1.__init__(self)
Base2.__init__(self)
where Base1 and Base2 are pybind11-exported classes.
This requires collapsing the various builtin base objects
(pybind11_object_56, ...) introduced in 2.1 into a single
pybind11_object of a fixed size; this fixed size object allocates enough
space to contain either a simple object (one base class & small* holder
instance), or a pointer to a new allocation that can contain an
arbitrary number of base classes and holders, with holder size
unrestricted.
* "small" here means having a sizeof() of at most 2 pointers, which is
enough to fit unique_ptr (sizeof is 1 ptr) and shared_ptr (sizeof is 2
ptrs).
To minimize the performance impact, this repurposes
`internals::registered_types_py` to store a vector of pybind-registered
base types. For direct-use pybind types (e.g. the `PyA` for a C++ `A`)
this is simply storing the same thing as before, but now in a vector;
for Python-side inherited types, the map lets us avoid having to do a
base class traversal as long as we've seen the class before. The
change to vector is needed for multiple inheritance: Python types
inheriting from multiple registered bases have one entry per base.