* ci: support Python 3.11-dev
Also update 3.10 to final, better PyPy usage
* fix: use PyFrame_GetCode on Python 3.9+
* ci: some bitiness of pypy not supported on win
* chore: update CMake support to 3.22rc1 to quiet warning
* fix: use dev version of py to fix Py 3.11
* tests: print proper Eigen version
* ci: include pypy2, not sure why
* ci: avoid running on Python 3.11 for now
* ci: fix runs
* ci: simpler PyPy usage, drop unmaintained scipy + pypy index
* ci: only binary numpy, wait on pypy 3.8
* refactor: address review
* fix: the types for return_value_policy_override in optional_caster
`return_value_policy_override` was not being applied correctly in
`optional_caster` in two ways:
- The `is_lvalue_reference` condition referenced `T`, which was the
`optional<T>` type parameter from the class, when it should have used `T_`,
which was the parameter to the `cast` function. `T_` can potentially be a
reference type, but `T` will never be.
- The type parameter passed to `return_value_policy_override` should be
`T::value_type`, not `T`. This matches the way that the other STL container
type casters work.
The result of these issues was that a method/property definition which used a
`reference` or `reference_internal` return value policy would create a Python
value that's bound by reference to a temporary C++ object, resulting in
undefined behavior. For reasons that I was not able to figure out fully, it
seems like this causes problems when using old versions of `boost::optional`,
but not with recent versions of `boost::optional` or the `libstdc++`
implementation of `std::optional`. The issue (that the override to
`return_value_policy::move` is never being applied) is present for all
implementations, it just seems like that somehow doesn't result in problems for
the some implementation of `optional`. This change includes a regression type
with a custom optional-like type which was able to reproduce the issue.
Part of the issue with using the wrong types may have stemmed from the type
variables `T` and `T_` having very similar names. This also changes the type
variables in `optional_caster` to use slightly more descriptive names, which
also more closely follow the naming convention used by the other STL casters.
Fixes#3330
* Fix clang-tidy complaints
* Add missing NOLINT
* Apply a couple more fixes
* fix: support GCC 4.8
* tests: avoid warning about unknown compiler for compilers missing C++17
* Remove unneeded test module attribute
* Change test enum to have more unique int values
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
* Adding MSVC C4127 suppression around Eigen includes.
* For MSVC 2015 only: also adding the C4127 suppression to test_eigen.cpp
* Copying original change from PR #3343, with extra line breaks to not run past 99 columns (our desired but currently not enforced limit).
* Fix `pybind11::object::operator=` to be safe if `*this` is accessible from Python
* Add `custom_type_setup` attribute
This allows for custom modifications to the PyHeapTypeObject prior to
calling `PyType_Ready`. This may be used, for example, to define
`tp_traverse` and `tp_clear` functions.
* Fix thread safety for pybind11 loader_life_support
Fixes issue: https://github.com/pybind/pybind11/issues/2765
This converts the vector of PyObjects to either a single void* or
a per-thread void* depending on the WITH_THREAD define.
The new field is used by each thread to construct a stack
of loader_life_support frames that can extend the life of python
objects.
The pointer is updated when the loader_life_support object is allocated
(which happens before a call) as well as on release.
Each loader_life_support maintains a set of PyObject references
that need to be lifetime extended; this is done by storing them
in a c++ std::unordered_set and clearing the references when the
method completes.
* Also update the internals version as the internal struct is no longer compatible
* Add test demonstrating threading works correctly.
It may be appropriate to run this under msan/tsan/etc.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Update test to use lifetime-extended references rather than
std::string_view, as that's a C++ 17 feature.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Make loader_life_support members private
* Update version to dev2
* Update test to use python threading rather than concurrent.futures
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Remove unnecessary env in test
* Remove unnecessary pytest in test
* Use native C++ thread_local in place of python per-thread data structures to retain compatability
* clang-format test_thread.cpp
* Add a note about debugging the py::cast() error
* thread_test.py now propagates exceptions on join() calls.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* remove unused sys / merge
* Update include order in test_thread.cpp
* Remove spurious whitespace
* Update comment / whitespace.
* Address review comments
* lint cleanup
* Fix test IntStruct constructor.
* Add explicit to constructor
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
* Adding a valgrind build on debug Python 3.9
Co-authored-by: Boris Staletic <boris.staletic@gmail.com>
* Add Valgrind suppression files
- Introduce suppression file, populate it with a first suppression taken from CPython, and fix one leak in the tests
- Suppress leak in NumPy
- More clean tests!
- Tests with names a-e passing (except for test_buffer)
- Suppress multiprocessing errors
- Merge multiprocessing suppressions into other suppression files
- Numpy seems to be spelled with a big P
- Append single entry from valgrind-misc.supp to valgrind-python.supp, and make clear valgrind-python.supp is only CPython
Co-authored-by: Boris Staletic <boris.staletic@gmail.com>
* Enable test_virtual_functions with a workaround
* Add a memcheck cmake target
- Add a memcheck cmake target
- Reformat cmake
- Appease the formatting overlords - they are angry
- Format CMake valgrind target decently
* Update CI config to new action versions
* fix: separate memcheck from pytest
* ci: cleanup
* Merge Valgrind and other deadsnakes builds
Co-authored-by: Boris Staletic <boris.staletic@gmail.com>
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* Adding missing virtual destructors, to silence clang -Wnon-virtual-dtor warnings.
Tested with clang version 9.0.1-12 under an Ubuntu-like OS.
Originally discovered in the Google-internal environment.
* adding -Wnon-virtual-dtor for GNU|Intel|Clang
* 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>
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
* tests: keep source dir clean
* ci: make first build inplace
* ci: drop dev setting (wasn't doing anything)
* tests: warn if source directory is dirty
* docs: move helpers to .github where allowed
* docs: more guidelines in CONTRIBUTING
* chore: update issue templates
* fix: review from @bstaletic
* refactor: a few points from @rwgk
* docs: more touchup, review changes
* tests: refactor and cleanup
* refactor: more consistent
* tests: vendor six
* tests: more xfails, nicer system
* tests: simplify to info
* tests: suggestions from @YannickJadoul and @bstaletic
* tests: restore some pypy tests that now pass
* tests: rename info to env
* tests: strict False/True
* tests: drop explicit strict=True again
* tests: reduce minimum PyTest to 3.1
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
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.
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).
* 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.
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`.
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`).
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.