* init
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Add constexpr to is_floating_point check
This is known at compile time so it can be constexpr
* Allow noconvert float to accept int
* Update noconvert documentation
* Allow noconvert complex to accept int and float
* Add complex strict test
* style: pre-commit fixes
* Update unit tests so int, becomes double.
* style: pre-commit fixes
* remove if (constexpr)
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* fix spelling error
* bump order in #else
* Switch order in c++11 only section
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* ci: trigger build
* ci: trigger build
* Allow casting from float to int
The int type caster allows anything that implements __int__ with explicit exception of the python float. I can't see any reason for this.
This modifies the int casting behaviour to accept a float.
If the argument is marked as noconvert() it will only accept int.
* tests for py::float into int
* Update complex_cast tests
* Add SupportsIndex to int and float
* style: pre-commit fixes
* fix assert
* Update docs to mention other conversions
* fix pypy __index__ problems
* style: pre-commit fixes
* extract out PyLong_AsLong __index__ deprecation
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* Add back env.deprecated_call
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* remove note
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* remove untrue comment
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* fix noconvert_args
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* resolve error
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Add comment
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* [skip ci]
tests: Add overload resolution test for float/int breaking change
Add test_overload_resolution_float_int() to explicitly test the breaking
change where int arguments now match float overloads when registered first.
The existing tests verify conversion behavior (int -> float, int/float -> complex)
but do not test overload resolution when both float and int overloads exist.
This test fills that gap by:
- Testing that float overload registered before int overload matches int(42)
- Testing strict mode (noconvert) overload resolution breaking change
- Testing complex overload resolution with int/float/complex overloads
- Documenting the breaking change explicitly
This complements existing tests which verify 'can it convert?' by testing
'which overload wins when multiple can convert?'
* Add test to verify that custom __index__ objects (not PyLong) work correctly with complex conversion. These should be consistent across CPython, PyPy, and GraalPy.
* Improve comment clarity for PyPy __index__ handling
Replace cryptic 'So: PYBIND11_INDEX_CHECK(src.ptr())' comment with
clearer explanation of the logic:
- Explains that we need to call PyNumber_Index explicitly on PyPy
for non-PyLong objects
- Clarifies the relationship to the outer condition: when convert
is false, we only reach this point if PYBIND11_INDEX_CHECK passed
above
This makes the code more maintainable and easier to understand
during review.
* Undo inconsequential change to regex in test_enum.py
During merge, HEAD's regex pattern was kept, but master's version is preferred.
The order of ` ` and `\|` in the character class is arbitrary. Keep master's order
(already fixed in PR #5891; sorry I missed looking back here when working on 5891).
* test_methods_and_attributes.py: Restore existing `m.overload_order(1.1)` call and clearly explain the behavior change.
* Reject float → int conversion even in convert mode
Enabling implicit float → int conversion in convert mode causes
silent truncation (e.g., 1.9 → 1). This is dangerous because:
1. It's implicit - users don't expect truncation when calling functions
2. It's silent - no warning or error
3. It can hide bugs - precision loss is hard to detect
This change restores the explicit rejection of PyFloat_Check for integer
casters, even in convert mode. This is more in line with Python's behavior
where int(1.9) must be explicit.
Note that the int → float conversion in noconvert mode is preserved,
as that's a safe widening conversion.
* Revert test changes that sidestepped implicit float→int conversion
This reverts all test modifications that were made to accommodate
implicit float→int conversion in convert mode. With the production
code change that explicitly rejects float→int conversion even in
convert mode, these test workarounds are no longer needed.
Changes reverted:
- test_builtin_casters.py: Restored cant_convert(3.14159) and
np.float32 conversion with deprecated_call wrapper
- test_custom_type_casters.py: Restored TypeError expectation for
m.ints_preferred(4.0)
- test_methods_and_attributes.py: Restored TypeError expectation
for m.overload_order(1.1)
- test_stl.py: Restored float literals (2.0) that were replaced with
strings to avoid conversion
- test_factory_constructors.py: Restored original constructor calls
that were modified to avoid float→int conversion
Also removes the unused avoid_PyLong_AsLong_deprecation fixture
and related TypeVar imports, as all uses were removed.
* Replace env.deprecated_call() with pytest.deprecated_call()
The env.deprecated_call() function was removed, but two test cases
still reference it. Replace with pytest.deprecated_call(), which is
the standard pytest context manager for handling deprecation warnings.
Since we already require pytest>=6 (see tests/requirements.txt), the
compatibility function is obsolete and pytest.deprecated_call() is
available.
* Update test expectations for swapped NoisyAlloc overloads
PR 5879 swapped the order of NoisyAlloc constructor overloads:
- (int i, double) is now placement new (comes first)
- (double d, double) is now factory pointer (comes second)
This swap is necessary because pybind11 tries overloads in order
until one matches. With int → float conversion now allowed:
- create_and_destroy(4, 0.5): Without the swap, (double d, double)
would match first (since int → double conversion is allowed),
bypassing the more specific (int i, double) overload. With the
swap, (int i, double) matches first (exact match), which is
correct.
- create_and_destroy(3.5, 4.5): (int i, double) fails (float → int
is rejected), then (double d, double) matches, which is correct.
The swap ensures exact int matches are preferred over double matches
when an int is provided, which is the expected overload resolution
behavior.
Update the test expectations to match the new overload resolution
order.
* Resolve clang-tidy error:
/__w/pybind11/pybind11/include/pybind11/cast.h:253:46: error: repeated branch body in conditional chain [bugprone-branch-clone,-warnings-as-errors]
253 | } else if (PyFloat_Check(src.ptr())) {
| ^
/__w/pybind11/pybind11/include/pybind11/cast.h:258:10: note: end of the original
258 | } else if (convert || PYBIND11_LONG_CHECK(src.ptr()) || PYBIND11_INDEX_CHECK(src.ptr())) {
| ^
/__w/pybind11/pybind11/include/pybind11/cast.h:283:16: note: clone 1 starts here
283 | } else {
| ^
* Add test coverage for __index__ and __int__ edge cases: incorrectly returning float
These tests ensure that:
- Invalid return types (floats) are properly rejected
- The fallback from __index__ to __int__ works correctly in convert mode
- noconvert mode correctly prevents fallback when __index__ fails
* Minor comment-only changes: add PR number, for easy future reference
* Ensure we are not leaking a Python error is something is wrong elsewhere (e.g. UB, or bug in Python beta testing).
See also: https://github.com/pybind/pybind11/pull/5879#issuecomment-3521099331
* [skip ci] Bump PYBIND11_INTERNALS_VERSION to 12 (for PRs 5879, 5887, 5960)
---------
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
Co-authored-by: gentlegiantJGC <gentlegiantJGC@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
* Add typing.SupportsIndex to int/float/complex type hints
This corrects a mistake where these types were supported but the type
hint was not updated to reflect that SupportsIndex objects are accepted.
To track the resulting test failures:
The output of
"$(cat PYROOT)"/bin/python3 $HOME/clone/pybind11_scons/run_tests.py $HOME/forked/pybind11 -v
is in
~/logs/pybind11_pr5879_scons_run_tests_v_log_2025-11-10+122217.txt
* Cursor auto-fixes (partial) plus pre-commit cleanup. 7 test failures left to do.
* Fix remaining test failures, partially done by cursor, partially manually.
* Cursor-generated commit: Added the Index() tests from PR 5879.
Summary:
Changes Made
1. **C++ Bindings** (`tests/test_builtin_casters.cpp`)
• Added complex_convert and complex_noconvert functions needed for the tests
2. **Python Tests** (`tests/test_builtin_casters.py`)
`test_float_convert`:
• Added Index class with __index__ returning -7
• Added Int class with __int__ returning -5
• Added test showing Index() works with convert mode: assert pytest.approx(convert(Index())) == -7.0
• Added test showing Index() doesn't work with noconvert mode: requires_conversion(Index())
• Added additional assertions for int literals and Int() class
`test_complex_cast`:
• Expanded the test to include convert and noconvert functionality
• Added Index, Complex, Float, and Int classes
• Added test showing Index() works with convert mode: assert convert(Index()) == 1 and assert isinstance(convert(Index()), complex)
• Added test showing Index() doesn't work with noconvert mode: requires_conversion(Index())
• Added type hint assertions matching the SupportsIndex additions
These tests demonstrate that custom __index__ objects work with float and complex in convert mode, matching the typing.SupportsIndex type hint added in PR
5891.
* Reflect behavior changes going back from PR 5879 to master. This diff will have to be reapplied under PR 5879.
* Add PyPy-specific __index__ handling for complex caster
Extract PyPy-specific __index__ backporting from PR 5879 to fix PyPy 3.10
test failures in PR 5891. This adds:
1. PYBIND11_INDEX_CHECK macro in detail/common.h:
- Uses PyIndex_Check on CPython
- Uses hasattr check on PyPy (workaround for PyPy 7.3.3 behavior)
2. PyPy-specific __index__ handling in complex.h:
- Handles __index__ objects on PyPy 7.3.7's 3.8 which doesn't
implement PyLong_*'s __index__ calls
- Mirrors the logic used in numeric_caster for ints and floats
This backports __index__ handling for PyPy, matching the approach
used in PR 5879's expand-float-strict branch.
* init
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* remove import
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* remove uneeded function
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* Add missing import
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* Fix type behind detailed_message_enabled flag
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Fix type behind detailed_message_enabled flag
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Add io_name comment
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Extra loops to single function
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* Remove unneeded forward declaration
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Switch variable name away from macro
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Switch variable name away from macro
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* Switch variable name away from macro
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* clang-tidy
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* remove stack import
* Fix bug in std::function Callable type
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* remove is_annotation argument
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
* Update function name and arg names
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
* style: pre-commit fixes
---------
Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Add `-DPYBIND11_WERROR=ON` to mingw cmake commands (and `-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON`).
* Using no-destructor idiom to side-step overzealous MINGW warning.
* Add __MINGW32__ pragma GCC diagnostic ignored in eigen.h
* Add another no-destructor workaround.
* Temporarily add -k (keep-going) flags to hopefully speed up finding all warnings.
* Revert "Temporarily add -k (keep-going) flags to hopefully speed up finding all warnings."
This reverts commit f36b0af8f9.
* Very minor shuffle to avoid MSVC warnings.
* Remove all `:BOOL` as suggested by @henryiii
* Don't return pointers to static objects with return_value_policy::take_ownership.
This fixes -Wfree-nonheap-object warnings produced by GCC.
* Use return value policy fix instead
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
* `#error BYE_BYE_GOLDEN_SNAKE`
* Removing everything related to 2.7 from ci.yml
* Commenting-out Centos7
* Removing `PYTHON: 27` from .appveyor.yml
* "PY2" removal, mainly from tests. C++ code is not touched.
* Systematic removal of `u` prefix from `u"..."` and `u'...'` literals. Collateral cleanup of a couple minor other things.
* Cleaning up around case-insensitive hits for `[^a-z]py.*2` in tests/.
* Removing obsolete Python 2 mention in compiling.rst
* Proper `#error` for Python 2.
* Using PY_VERSION_HEX to guard `#error "PYTHON 2 IS NO LONGER SUPPORTED.`
* chore: bump pre-commit
* style: run pre-commit for pyupgrade 3+
* tests: use sys.version_info, not PY
* chore: more Python 2 removal
* Uncommenting Centos7 block (PR #3691 showed that it is working again).
* Update pre-commit hooks
* Fix pre-commit hook
* refactor: remove Python 2 from CMake
* refactor: remove Python 2 from setup code
* refactor: simplify, better static typing
* feat: fail with nice messages
* refactor: drop Python 2 C++ code
* docs: cleanup for Python 3
* revert: intree
revert: intree
* docs: minor touchup to py2 statement
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
* Adding readability-qualified-auto to .clang-tidy
Ported from @henryiii's 287527f705
* fix: support Python < 3.6
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
* Expand string_view support to str, bytes, memoryview
1. Allows constructing a str or bytes implicitly from a string_view;
this is essentially a small shortcut allowing a caller to write
`py::bytes{sv}` rather than `py::bytes{sv.data(), sv.size()}`.
2. Allows implicit conversion *to* string_view from py::bytes -- this
saves a fair bit more as currently there is no simple way to get such
a view of the bytes without copying it (or resorting to Python API
calls).
(This is not done for `str` because when the str contains unicode we
have to allocate to a temporary and so there might not be some string
data we can properly view without owning.)
3. Allows `memoryview::from_memory` to accept a string_view. As with
the other from_memory calls, it's entirely your responsibility to
keep it alive.
This also required moving the string_view availability detection into
detail/common.h because this PR needs it in pytypes.h, which is higher
up the include chain than cast.h where it was being detected currently.
* Move string_view include to pytypes.h
* CI-testing a fix for the "ambiguous conversion" issue.
This change is known to fix the `tensorflow::tstring` issue reported under https://github.com/pybind/pybind11/pull/3521#issuecomment-985100965
TODO: Minimal reproducer for the `tensorflow::tstring` issue.
* Make clang-tidy happy (hopefully).
* Adding minimal reproducer for the `tensorflow::tstring` issue.
Error without the enable_if trick:
```
/usr/local/google/home/rwgk/forked/pybind11/tests/test_builtin_casters.cpp:169:16: error: ambiguous conversion for functional-style cast from 'TypeWithBothOperatorStringAndStringView' to 'py::bytes'
return py::bytes(TypeWithBothOperatorStringAndStringView());
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/google/home/rwgk/forked/pybind11/include/pybind11/detail/../pytypes.h:1174:5: note: candidate constructor
bytes(const std::string &s) : bytes(s.data(), s.size()) { }
^
/usr/local/google/home/rwgk/forked/pybind11/include/pybind11/detail/../pytypes.h:1191:5: note: candidate constructor
bytes(std::string_view s) : bytes(s.data(), s.size()) { }
^
```
* Adding missing NOLINTNEXTLINE
* Also apply ambiguous conversion workaround to str()
Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
* Removing all MSVC C4127 warning suppression pragmas.
* Removing MSVC /WX (WERROR). To get a full list of all warnings.
* Inserting PYBIND11_SILENCE_MSVC_C4127. Changing one runtime if to #if.
* Changing PYBIND11_SILENCE_MSVC_C4127 macro to use absolute namespace (for use outside pybind11 include directory).
* Restoring MSVC /WX (WERROR).
* Removing globally-scoped suppression for clang -Wunsequenced. Based on an experiment under PR #3202 it is obsolete and can simply be removed.
* 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()
* 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
* style: clang tidy fix
* style: fix missing NOLINT
* ICC: Update Compiler Name
Changed upstream with the last oneAPI release.
* ICC CI: Downgrade pytest
pytest 6 does not capture the `discard_as_unraisable` stderr and
just writes a warning with its content instead.
* Use new test pinning requirements.txt
* tests: add notes about intel, cleanup
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.
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.
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 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
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.
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 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.