Commit Graph

1479 Commits

Author SHA1 Message Date
Aaron Gokaslan
3893f37bce
maint(clang-tidy): Bugprone enable checks (#3166)
* Enable bugprone checks

* Reset delta and massage config

* Start to apply bugprone fixes

* try to fix minor bug

* Fix later

* Fix perfect forwarding bugprone

* Remove nolint

* undo constructor delete

* Fix bugprone-perfect-forwarding again

* Remove TODO

* Add another nolint for bugprone-exception-escape in scoped interpreter

* Fix remaining bugprone errors

* Properly apply bugprone-macro-parantheses

* Redo formatting and remove bugprone nolint

* Add coment and revert more whitespace changes

* Fix typo

* Fix parsing bug

* Add back comma

* Fix clang-tidy issue

* Apply remaining clang-tidy fixes
2021-08-06 14:30:28 -04:00
Henry Schreiner
089328f779 Revert "fix: apply simpler expression with fewer workarounds"
This reverts commit 1fafd1b447.
2021-08-06 13:09:48 -04:00
Henry Schreiner
1fafd1b447
fix: apply simpler expression with fewer workarounds 2021-08-06 13:03:26 -04:00
Henry Schreiner
5f4d725918
fix: version number hex 2021-08-03 17:03:11 -04:00
Henry Schreiner
c30f57d2ed
chore: start development for 2.8.0 2021-08-03 16:11:07 -04:00
Henry Schreiner
82adacb31d
fix: include hex version in bump 2021-08-03 15:20:23 -04:00
Henry Schreiner
5f34c42d70 chore: bump to version 2.7.1 2021-08-03 15:06:57 -04:00
Aaron Gokaslan
c0756ccd93
fix: func_handle for rule of two (#3169)
* Fix func_handle for rule of two

* Apply reviewer suggestion
2021-08-03 13:15:48 -04:00
Ralf W. Grosse-Kunstleve
dcbda8d7ff
Removing MSVC C4127 from pragma block at the top of pybind11.h (#3152)
* Removing pragma for 4127 (to see what is still broken with the latest code).

* Using new constexpr_bool() to suppress warning C4127.

* One missed case, Python 2 only.

* PYBIND11_SILENCE_MSVC_C4127 (more similar to the approach for C4100).
2021-07-30 11:25:29 -07:00
Ralf W. Grosse-Kunstleve
e2573dc961
Moving pragma for MSVC warning C4505 from pybind11.h to existing list in detail/common.h (#3160)
* Moving pragma for C4505 from pybind11.h to existing list in detail/common.h.

* Removing 4 existing suppressions to 1. see what is still needed and 2. capture the MSVC messages.

* It turns out none of the 4 pragmas are needed anymore.
2021-07-30 10:51:50 -07:00
Jerome Robert
9e8a741baa
fix: Mingw64 corrected and add a CI job to test it (#3132)
* mingw64 platform string is like mingw_xxx not "mingw"

See https://github.com/msys2/MINGW-packages/blob/master/mingw-w64-python/0099-Change-the-get_platform-method-in-sysconfig-and-dist.patch

* Mingw: Do not dllexport exceptions

This is a fix for errors like:

D:/a/pybind11/pybind11/include/pybind11/detail/common.h:735:23: error: 'dllexport' implies default visibility, but 'class pybind11::builtin_exception' has already been declared with a different visibility
  735 | class PYBIND11_EXPORT builtin_exception : public std::runtime_error {
      |                       ^~~~~~~~~~~~~~~~~

* GHA: Test Mingw64 build

* fix: avoid thin binaries on mingw

* fix: drop lto on MinGW

* Mingw64: disable PYBIND11_DEPRECATED

It trigger many warnings for unknown reasons

Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
2021-07-30 13:48:41 -04:00
Ralf W. Grosse-Kunstleve
b42597291f
Limiting pragma for ignoring GCC 7 -Wnoexcept-type to the scope of pybind11.h. (#3161)
* Moving pragma for ignoring -Wnoexcept-type to the one location where it is needed.

* Trying a second location.

* The previous commit worked (GitHub Actions green), but see the added comment about the dicy nature of -Wnoexcept-type ("if and only if").

* Applying reviewer suggestion.
2021-07-30 07:09:55 -07:00
Ralf W. Grosse-Kunstleve
b72ca7d1bd
Removing MSVC C4100 from pragma block at the top of pybind11.h (#3150)
* Removing pragma for 4100 (to see what is still broken with the latest code).

* Adding --keep-going

* Revert "Adding --keep-going"

This reverts commit 1c844c6ffd07a6111b644811e7e3b0a50b9d44bb.

* Introducing PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100.

* _MSC_VER <= 1916

* Replacing simple variadic function with variadic template (attempt to resolve MSVC 2017 failures).

* Preserving existing comment (moved from pybind11.h to detail/common.h).

* Adding blank lines for readability.
2021-07-28 17:01:21 -07:00
Ralf W. Grosse-Kunstleve
f4721a7b44
Accommodating environments that define __STDC_WANT_LIB_EXT1__ even if __STDC_LIB_EXT1__ is not defined by the implementation. (#3151)
Follow-on to PR #3129.
2021-07-28 08:58:36 -07:00
Ralf W. Grosse-Kunstleve
2164c2e0e7
Removing __INTEL_COMPILER section from pragma block at the top of pybind11.h (#3135)
* Fixing `pragma warning pop` for `__INTEL_COMPILER`.

* Adding push/pop to 3 tests. Removing #878 from top of pybind11.h (it was/is only needed for 1 test).

* Trying again after CI failure, moving the push to the top of 2 tests.

* Trying more after CI failure, adding push/pop to pybind11_tests.h, constructor_stats.h.

* Moving ICC #2196 suppression to CMakeLists.txt

* Fixing condition for `pragma GCC diagnostic push` in pybind11.h

* Moving `pragma warning disable 2196` to common.h

* Revising #ifdef to be more conservative.

* Undoing insertion of notes that will hopefully soon be completely obsolete anyway.
2021-07-27 15:33:31 -07:00
Aaron Gokaslan
9beaa925db
maint(clang-tidy): Improve code readability with explicit boolean casts (#3148)
* maint(clang-tidy) Improve code readability

* Fix minor typos

* Revert optimization that removed test case

* Fix comment formatting

* Revert another optimization to repro an issue

* Remove make_unique since it C++14 and newer only

* eformat comments

* Fix unsignedness of comparison

* Update comment
2021-07-27 15:32:26 -07:00
David Hewitt
a0b975965f
Allow python builtins to be used as callbacks (#1413)
* Allow python builtins to be used as callbacks

* Try to fix pypy segfault

* Add expected fail for PyPy

* Fix typo

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add more info to xfail

* Add env

* Try returning false

* Try removing the move for pypy

* Fix bugs

* Try removing move

* Just keep ignoring for PyPy

* Add back xfail

* Fix ctors

* Revert change of std::move

* Change to skip

* Fix bug and edit comments

* Remove clang-tidy bugprone fix skip bug

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2021-07-27 14:16:28 -04:00
Ralf W. Grosse-Kunstleve
a0f862d428
Removing MSVC C4800 from pragma block at the top of pybind11.h (#3141)
* Adding PYBIND11_COMPAT_BOOL_CAST to appease MSVC 2015 warning C4800.

* Replacing PYBIND11_COMPAT_BOOL_CAST with simpler != 0

* Extra parentheses (almost all compilers failed without these).
2021-07-26 13:26:36 -07:00
Ralf W. Grosse-Kunstleve
7904ba1a5c
Adding pragma warning(disable: 4522) for MSVC <= 2017. (#3142) 2021-07-26 12:02:50 -07:00
Ralf W. Grosse-Kunstleve
ff97f101d9
Removing MSVC C4996 from pragma block at the top of pybind11.h (#3129)
* Removing MSVC C4996 from pragma block at the top of pybind11.h

* localtime_thread_safe, PYBIND11_COMPAT_STRDUP

* Adding #include <ctime> (attempt to fix MSVC 2015, 2017 errors).
2021-07-26 11:28:36 -07:00
jesse-sony
d65edfb024
Feature/local exception translator (#2650)
* Create a module_internals struct

Since we now have two things that are going to be module local, it felt
correct to add a struct to manage them.

* Add local exception translators

These are added via the  register_local_exception_translator function
and are then applied before the global translators

* Add unit tests to show the local exception translator works

* Fix a bug in the unit test with the string value of KeyError

* Fix a formatting issue

* Rename registered_local_types_cpp()

Rename it to get_registered_local_types_cpp() to disambiguate from the
new member of module_internals

* Add additional comments to new local exception code path

* Add a register_local_exception function

* Add additional unit tests for register_local_exception

* Use get_local_internals like get_internals

* Update documentation for new local exception feature

* Add back a missing space

* Clean-up some issues in the docs

* Remove the code duplication when translating exceptions

Separated out the exception processing into a standalone function in the
details namespace.

Clean-up some comments as per PR notes as well

* Remove the code duplication in register_exception

* Cleanup some formatting things caught by clang-format

* Remove the templates from exception translators

But I added a using declaration to alias the type.

* Remove the extra local from local_internals variable names

* Add an extra explanatory comment to local_internals

* Fix a typo in the code
2021-07-21 05:22:18 -07:00
blacktea
6d5d4e738c
Move object in pop method of List. (#3116)
* Move item instead of copy.

* Make Clang 3.6 happy.

Co-authored-by: c99 <email@dummy.com>
2021-07-20 11:48:09 -04:00
Ralf W. Grosse-Kunstleve
34f587dd23
Removing all warning pragmas that have not effect. (#3127) 2021-07-17 08:54:31 -07:00
Henry Schreiner
74935f8d67
chore: post-release (#3128) 2021-07-17 11:50:42 -04:00
Henry Schreiner
65e95ea867
chore: bump to 2.7.0 (#3123) 2021-07-16 09:27:47 -04:00
Ralf W. Grosse-Kunstleve
4359e00b97
Introducing PYBIND11_VERSION_HEX (#3120)
* Introducing PYBIND11_VERSION_HEX (better late than never!)

* PYBIND11_VERSION_HEX consistency check in setup.py
2021-07-15 15:00:57 -07:00
Boris Staletic
5cd3750757
Enable -Wstrict-aliasing warning (#2816)
* Enable -Wstrict-aliasing warning

* Narrow down the scope of -Wstrict-aliasing

* Go home, MSVC, you're drunk

* Make sure "pragma GCC" is not executed on ICC

Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
2021-07-15 12:38:52 -04:00
Shane Loretz
7331d381af
Raise codec errors when casting to std::string (#2903)
* Raise codec errors when casting to std::string

Allow the codec's exception to be raised instead of RuntimeError when
casting from py::str to std::string.

PY2 allows ucs surrogates in UTF-8 conversion

Signed-off-by: Shane Loretz <sloretz@openrobotics.org>
Signed-off-by: Shane Loretz <sloretz@osrfoundation.org>

* Attempt to fix py2 error

* Revert all unicode literals

* Fixed

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2021-07-13 21:21:55 -07:00
Ralf W. Grosse-Kunstleve
aca6c3ba37
* Removing stray semicolons (discovered by running clang-format v12 followed by tools/check-style.sh). (#3087)
* Manually moving `// NOLINT` comments so that clang-format does not move them to the wrong places.

* Manually reformatting comments related to `static_assert`s so that clang-format does not need two passes.

* Empty lines between #includes, to prevent clang-format from shuffling the order and thereby confusing MSVC 2015.

* git diff -U0 --no-color HEAD^ | python3 $HOME/clone/llvm-project/clang/tools/clang-format/clang-format-diff.py -p1 -style=file -i
2021-07-13 18:14:58 -07:00
jbarlow83
2b7985e548
Improve documentation of discard_as_unraisable() API (#2697)
* Improve documentation of discard_as_unraisable() API

* Update pytypes.h

Remove "the above"

* Update pytypes.h

Fix precommit error

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2021-07-13 15:32:56 -04:00
Aaron Gokaslan
25e470c57d
fix(clang-tidy): Add cppcoreguidelines-init-vars,slicing, and throw-by-value-catch-by-reference checks (#3094)
* clang-tidy: guard against more UB behavior

* Remove slicing check for now
2021-07-13 09:54:32 -04:00
Henry Schreiner
f0a65c899c
docs(fix): spelling mistake in recent commit 2021-07-12 16:57:28 -04:00
Ralf W. Grosse-Kunstleve
7472d37a93
Adding iostream.h thread-safety documentation. (#2995)
* Adding iostream.h thread-safety documentation.

* Restoring `TestThread` code with added `std::lock_guard<std::mutex>`.

* Updating new comments to reflect new information.

* Fixing up `git rebase -X theirs` accidents.
2021-07-12 13:39:06 -07:00
Aaron Gokaslan
b5357d1fa8
fix(clang-tidy): Enable clang-tidy else-after-return and redundant void checks (#3080)
* Enable clang-tidy else-after-return and redundant void checks

* Fix remaining else-after

* Address reviewer comments

* Fix indentation

* Rerun clang-tidy post merge
2021-07-09 06:45:53 -07:00
Ralf W. Grosse-Kunstleve
6d1b197b46
Splitting out pybind11/stl/filesystem.h. (#3077)
* Splitting out pybind11/stl/filesystem.h.

To solve breakages like: https://github.com/deepmind/open_spiel/runs/2999582108

Mostly following the suggestion here: https://github.com/pybind/pybind11/pull/2730#issuecomment-750507575

Except using pybind11/stl/filesystem.h instead of pybind11/stlfs.h, as decided via chat.

stl.h restored to the exact state before merging PR #2730 via:
```
git checkout 733f8de24f stl.h
```

* Properly including new stl subdirectory in pip wheel config.

This now passes interactively:
```
pytest tests/extra_python_package/
```

* iwyu cleanup.

iwyuh.py -c -std=c++17 -DPYBIND11_TEST_BOOST -Ipybind11/include -I/usr/include/python3.9 -I/usr/include/eigen3 include/pybind11/stl/filesystem.h

* Adding PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL.

* Eliminating else after return.
2021-07-08 09:02:48 -07:00
Robert Haschke
c090c8c409
Unify cast_error message thrown by [simple|unpacking]_collector (#3013)
* Unify cast_error message thrown by [simple|unpacking]_collector

simple_collector and unpacking_collector throw different error messages
when the casting of an argument failed: While the former mentions make_tuple(),
the latter emphasises the call argument (and its name/position).

* Consolidating "Unable to convert call argument" error reporting code to guarantee uniformity.

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2021-07-06 15:13:13 -07:00
luzpaz
8bee61b645
docs: fix various typos (#3075)
Found via `codespell -q 3 -L nd,ot,thist`
2021-07-04 19:58:35 -04:00
Dustin Spicuzza
6d4409466b
Check dict item accesses where it isn't already checked (#2863)
* Convert PyDict_GetXXX to internal error checking variant

* Check unlikely error return from PyDict_DelItemString
2021-07-02 07:02:33 -07:00
Antony Lee
5bcaaa0423
Add a std::filesystem::path <-> os.PathLike caster. (#2730) 2021-07-02 07:00:50 -07:00
cyy
f067deb563
avoid unnecessary strlen (#3058) 2021-06-30 23:35:25 -07:00
jonathan-conder-sm
733f8de24f
Avoid string copy if possible when passing a Python object to std::ostream (#3042) 2021-06-30 22:19:14 -07:00
Ralf W. Grosse-Kunstleve
fbae8f313b
pickle setstate: setattr __dict__ only if not empty (#2972)
* pickle setstate: setattr __dict__ only if not empty, to not force use of py::dynamic_attr() unnecessarily.

* Adding unit test.

* Clang 3.6 & 3.7 compatibility.

* PyPy compatibility.

* Minor iwyu fix, additional comment.

* Addressing reviewer requests.

* Applying clang-tidy suggested fixes.

* Adding check_dynamic_cast_SimpleCppDerived, related to issue #3062.
2021-06-30 12:34:32 -07:00
Cris Luengo
93e69191c1
fix: enable py::implicitly_convertible<py::none, ...> for py::class_-wrapped types (#3059)
* Allow casting from None to a custom object, closes #2778

* ci.yml patch from the smart_holder branch for full CI coverage.
2021-06-25 17:56:17 -07:00
Aaron Gokaslan
dac74ebdf5
fix(clang-tidy): performance fixes applied in tests and CI (#3051)
* Initial fixes

* Whoops

* Finish clang-tidy manual fixes

* Add two missing fixes

* Revert

* Update clang-tidy

* Try to fix unreachable code error

* Move nolint comment

* Apply missing fix

* Don't override clang-tidy config

* Does this fix clang-tidy?

* Make all clang-tidy errors visible

* Add comments about NOLINTs and remove a few

* Fix typo
2021-06-22 12:11:54 -04:00
Aaron Gokaslan
3b30b0a51e
fix(clang-tidy): clang-tidy readability and misc fixes, like adding const (#3052)
* Enable and apply clang-tidy readability and misc fixes.

* Revert deprecated tester

* add space to tests/test_constants_and_functions.cpp
2021-06-21 10:37:48 -04:00
Aaron Gokaslan
af6218ff78
fix(clang-tidy): Apply performance fixes from clang-tidy (#3046)
* Apply performance fixes from clang-tidy

* 2nd Round of Perf Optimizations

* 3rd round of fixes & handle false-positive

* Apply missing fix and clang-format

* Apply reviewer comment
2021-06-19 10:53:27 -07:00
Jack S. Hale
4c7697dbe9
Add const T to docstring generation. (#3020)
* Add const T to docstring generation.

* Change order.

* See if existing test triggers for a const type.

* Add tests.

* Fix test.

* Remove experiment.

* Reformat.

* More tests, checks run.

* Adding `test_fmt_desc_` prefix to new test functions.

* Using pytest.mark.parametrize to 1. condense test; 2. exercise all functions even if one fails; 3. be less platform-specific (e.g. C++ float is not necessarily float32).

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2021-06-08 11:56:45 -07:00
Yichen
3ac690b88b
Explicitly export exception types. (#2999)
* Set visibility of exceptions to default.

Co-authored-by: XZiar <czktc2007@gmail.com>

* add test

* update docs

* Skip failed test.
2021-05-27 08:00:18 -07:00
Pieter P
0c93a0f3fc
Fix Unicode support for ostream redirects (#2982)
* Crash when printing Unicode to redirected cout
Add failing tests

* Fix Unicode crashes redirected cout

* pythonbuf::utf8_remainder check end iterator

* Remove trailing whitespace and formatting iostream

* Avoid buffer overflow if ostream redirect races
This doesn't solve the actual race, but at least it now has a much lower
probability of reading past the end of the buffer even when data races
do occur.
2021-05-03 22:04:38 -07:00
mvoelkle-cern
e08a58111d
Fix compilation with gcc < 5 (#2956)
When the user defines _GLIBCXX_USE_CXX11_ABI=0 to force the pre-c++11 ABI, numpy.h assumes that is_trivially_copyable is available.
It is not necessarily the case. This patch uses clang's feature detection instead.
The workaround is for certain libstdc++ versions, so the test should target these particular versions.
2021-04-19 13:53:57 -04:00
Philipp Bucher
62976cfcb8
fix: using -Werror-all for Intel (#2948)
* correcting Werror for Intel

* adding ward for Intel

* adding wards for intel

* another ward for Intel

* missed one intel ward

* exact match for intel compiler

* removing inline limits

* disable warnings about inline limits

* formatter suggestion

* more indent

* hopefully make formatter happy

* addressed review

* fix &&

* Update tests/CMakeLists.txt

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2021-04-14 14:01:27 -04:00
Tamaki Nishino
6709abba93
Allow function pointer extraction from overloaded functions (#2944)
* Add a failure test for overloaded functions

* Allow function pointer extraction from overloaded functions
2021-04-13 16:53:56 -07:00
Ralf W. Grosse-Kunstleve
ad6bf5cd39
Adding PyGILState_Check() in object_api<>::operator(). (#2919)
* 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()`.
2021-04-02 18:17:12 -07:00
Robert Haschke
c2db53da56
fix: catch missing self argument in overloads constructor (#2914) 2021-04-02 13:13:44 -04:00
Boris Staletic
f110889dde
Use correct duration representation when casting from datetime.timdelta to std::chrono::duration (#2870)
* 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
2021-03-07 23:42:01 -08:00
Bertrand MICHEL
74a767d429
Dtype kind vs char (#2864)
* [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>
2021-02-23 10:57:28 +01:00
Dustin Spicuzza
c0fbb02c9f
Extract gil management functions to separate header (#2845) 2021-02-22 19:15:40 -08:00
Ralf W. Grosse-Kunstleve
0c42250a4e
Splitting out detail/type_caster_base.h from cast.h, with iwyu cleanup. (#2841)
* Splitting out detail/type_caster_base.h from cast.h.
* Include cleanup guided by include-what-you-use 0.12 based on clang version 9.0.1-11.
2021-02-22 18:38:18 -08:00
Vikram Pal
417067eeb8
Add pybind11::bytearray (#2799)
* Add initial implementation

* Add few more methods

* Add tests

* Fix a typo

* Use std::string constructor which takes size

* Fix implicit sign conversion error

* Add size method and test

* Remove implicit conversion

* Fix bytearray constructors and operator std::string()

* Make implicit bytearray constructor explicit

* Rerun tests

* Add null check

* Rerun tests

* Rerun tests - 2

* Remove NULL check
2021-02-14 15:51:13 +01:00
Karthik Nishanth
e791ec4e27
fix: add null pointer check with std::localtime (#2846) 2021-02-08 15:38:22 -05:00
Yannick Jadoul
6cf6bf203e
Fix confusing weakref constructor overload (#2832)
* 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
2021-01-31 23:13:31 +01:00
Ralf W. Grosse-Kunstleve
932769b038
Adding holder_caster typename SFINAE = void hooks to help work around the current lack of smart-pointer interoperability (#2833)
* 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.
2021-01-30 12:02:24 -08:00
Edward Lockhart
23c3edcf21
When determining if a shared_ptr already exists, use a test on the we… (#2819)
* 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>
2021-01-30 20:05:13 +01:00
Ralf W. Grosse-Kunstleve
0432ae7c52
Changing pybind11::str to exclusively hold PyUnicodeObject (#2409)
* Changing pybind11::str to exclusively hold PyUnicodeObject
2021-01-29 09:41:42 -08:00
Yannick Jadoul
587d5f840a
Update breathe to 4.26.1, add make_tuple, make_iterator, and make_key_iterator (#2828) 2021-01-28 12:28:16 +01:00
Ralf W. Grosse-Kunstleve
9b7bfef833
Factoring out find_registered_python_instance() from type_caster_generic::cast. (#2822)
Factoring out find_registered_python_instance() from type_caster_generic::cast.
2021-01-26 21:08:46 -08:00
Henry Fredrick Schreiner
87954e7a54 fix: corrected dev versioning 2021-01-26 22:42:14 -05:00
Henry Fredrick Schreiner
4a5b81b1b7 chore: get back to work 2021-01-26 22:28:09 -05:00
Henry Schreiner
8de7772cc7
chore: prepare for the 2.6.2 release (#2821) 2021-01-26 21:26:45 -05:00
Henry Fredrick Schreiner
732bf88d19 fix: avoid changing class outside of GIL 2021-01-26 20:59:27 -05:00
Yannick Jadoul
0bb8ca2639
Always call PyNumber_Index when casting from Python to a C++ integral type, also pre-3.8 (#2801)
* 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
2021-01-25 21:05:17 +01:00
crimsoncor
9ea39dc356
Force the builtin module key to be the correct type. (#2814)
* 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>
2021-01-24 09:17:28 -08:00
Henry Fredrick Schreiner
5b43ac42a0 docs: fix missing line from #2310 2021-01-19 19:56:22 -05:00
Henry Schreiner
2db0264aca
style: add clang-format file (#2310)
* style: adding clang-format as manual hook

* docs: adding a Clang-Format section. (#2803)

Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2021-01-19 19:10:26 -05:00
Michael Kuron
48534089f7
fix: Intel ICC C++17 compatibility (#2729)
* 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>
2021-01-17 19:53:07 -05:00
Yannick Jadoul
8449a8089c
fix: only allow integer type_caster to call __int__ method when conversion is allowed; always call __index__ (#2698)
* 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()
2021-01-16 20:52:14 -05:00
Yannick Jadoul
0855146357
Plug leaking function_records in cpp_function initialization in case of exceptions (found by Valgrind in #2746) (#2756)
* 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
2021-01-14 19:34:32 +01:00
Andy Maloney
40931961e3
docs: fix spelling in some comments/docs (#2777)
Found with codespell
2021-01-13 23:15:58 -05:00
Andy Maloney
df8494dc86
fix: a clang warning [-Wshadow-field-in-constructor-modified] (#2780)
* 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
2021-01-13 23:15:27 -05:00
Changming Sun
210c8c218f
fix: a warning found by static code analyzer (#2783)
* 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>
2021-01-13 23:14:06 -05:00
Yannick Jadoul
e57dd4717e
Fix various minor memory leaks in the tests (found by Valgrind in #2746) (#2758)
* 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
2021-01-01 17:05:22 +01:00
Yannick Jadoul
e612043d43
Fix invalid access when reinterpret_casting a non-pybind11 PyObject* to instance* (found by Valgrind in #2746) (#2755) 2020-12-31 17:10:11 +01:00
Eric Cousineau
2110d2d8ba
enum: add missing Enum.value property (#2739)
* enum: Add Enum.value property

* simplify

* address review
2020-12-31 11:08:15 -05:00
Qifan Lu
d587a2fd17
fix: do not set docstring for function when empty (#2745)
* Do not set docstring for function when it's empty

* No need to check pointer for `free`

* Use ternary operator to conditionally set `ml_doc`
2020-12-27 22:56:30 -05:00
Nikita Shulga
79cb013f1f
fix: allow users to avoid thread termination in scoped_released (#2657)
* 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>
2020-12-19 15:45:19 -05:00
Yannick Jadoul
30eb39ed79
fix: also throw in the move-constructor added by the PYBIND11_OBJECT macro, after the argument has been moved-out (if necessary) (#2701) 2020-12-15 23:22:53 -05:00
Robert Haschke
d9fa70561e
style: remove redundant instance->owned = true (#2723)
which was just before set to True in instance->allocate_layout()
2020-12-15 23:21:40 -05:00
Laramie Leavitt
5469c238c8
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.
2020-12-15 16:53:55 -08:00
Boris Staletic
8adef2c7f6
fix: workaround for #2682 and #2422 by simply clearing the TypeError (#2685) 2020-11-23 14:02:25 -05:00
albanD
087b07c8b7
Remove workaround code that is not needed since #1211 (#2683) 2020-11-23 14:00:35 -05:00
Tobias Leibner
7bd4b39754
fix: define PYBIND11_CPP14 for recent intel compilers (#2679) 2020-11-23 09:11:04 -05:00
nickbridgechess
2fa4747cd4
pythonbuf fix (#2675)
* Added test_thread testing for ostream_redirect segfault recreation

* fix: scoped_ostream_redirect str created outside gil

* Moved threading tests into test_iostream. Cleaned up some formatting. Deleted test_thread.{cpp,py}

* CI: few formatting fixes

* CI: yet another formatting fix

* CI: more formatting fixes. Removed unecessary comment

* Ignore 'warning C4702: unreachable code' in MSVC 2015

Co-authored-by: Nick Bridge <nick.bridge.chess@gmail.com>
Co-authored-by: Nick Bridge <nbridge@jumptrading.com>
Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net>
2020-11-19 12:09:33 +01:00
Henry Schreiner
b7c741b540 docs: back to work after 2.6.1 2020-11-11 19:27:41 -05:00
Henry Schreiner
f1abf5d915
docs: changelog update (#2652) 2020-11-11 16:33:21 -05:00
Yannick Jadoul
c58758d049
fix: add reasonable argument names to enum_ methods (#2637)
* Add argument names to enum_ methods

* Add test_enum::test_docstring_signatures
2020-11-10 12:49:42 -05:00
Robert Haschke
b72cebeb22
style: clang-tidy: modernize-use-using (#2645)
* style: clang-tidy: modernize-use-using

* style: more clang-tidy checking

Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
2020-11-09 10:10:19 -08:00
Boris Staletic
06b673a0da
Allow NULL value in pybind11_meta_setattro (#2629) 2020-11-05 23:54:37 +01:00
Yannick Jadoul
7d6713a46d
Use weakref to clean up captured function object in def_buffer (#2634) 2020-11-02 18:39:40 +01:00
Thomas Köppe
f2e799863b
[common.h] Mark another entry point as "unused". (#2625) 2020-10-29 12:47:59 +01:00
Yannick Jadoul
3a37d33830
Add __builtins__ to globals argument of py::exec and py::eval if not present (#2616)
* Add __builtins__ to globals argument of `py::exec` and `py::eval` if not present

* Refactor into inline ensure_builtins_in_globals function
2020-10-27 19:58:27 +01:00
Wenzel Jakob
86d3e9eb43 begin working towards a future v2.6.1 patch release 2020-10-21 18:31:10 +02:00
Wenzel Jakob
59a2ac2745 v2.6.0 release 2020-10-21 18:07:48 +02:00
Boris Staletic
4038542b15
Remove friend declaration of py::class_ in py::detail::generic_type (#2613)
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.

&nbsp;

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.
2020-10-21 13:14:56 +02:00
Mana Borwornpadungkitti
6edd0e6d90
fix: Reject keyword argument None with .none(false) (#2611)
* 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>
2020-10-20 23:57:22 +02:00
Henry Schreiner
c16da99309 chore: bump to 2.6.0rc3 2020-10-16 17:34:53 -04:00
Henry Schreiner
064362fbb7
fix: allow the ABI string to be forced (#2602) 2020-10-16 17:23:36 -04:00
Yannick Jadoul
6364b732e9
fix: test_factory_constructors.py failure triggered by test_register_duplicate_class (#2564)
* 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
2020-10-16 16:38:51 -04:00
Henry Schreiner
6bb71c48d5 fix: more intp asserts, reinterpret_cast 2020-10-15 17:38:49 -04:00
Henry Schreiner
9ac604a3e8 fix: PyPy windows issue 2020-10-15 17:38:49 -04:00
Henry Schreiner
b72c79f964 fix: std::is_pod -> pybind11::detail::is_pod 2020-10-15 17:38:49 -04:00
Henry Schreiner
c4a8b5bb91 chore: bump to 2.6.0rc2 2020-10-14 16:37:25 -04:00
Yannick Jadoul
493649f965
fix: valgrind-detected after-freeing access of PyMethodDef (macOS Python 3.9.0 segfaults) (#2576)
* Check if valgrind-detected after-freeing access of PyMethodDef causes macOS Python 3.9 segfaults

* fix: only apply leak on 3.9.0

* fix: faster check

* fix: better naming thanks to @bstaletic

Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
2020-10-14 14:11:09 -04:00
Yannick Jadoul
99773fc5f6
fix: throw error_already_set in py::len on failing PyObject_Length (#2575)
* Throw error_already_set in py::len on failing PyObject_Length

* Fix tests to mach error message on PyPy
2020-10-12 23:00:54 -04:00
Yannick Jadoul
1914b7d3a7
Shorten PYBIND11_EMBEDDED_MODULE macro implementation by using PYBIND11_CATCH_INIT_EXCEPTIONS (#2579) 2020-10-12 23:10:18 +02:00
Henry Schreiner
993495c96c
fix: Intel 18+ required (#2577)
* fix: Intel 18+ fully supported

* fix: Intel compiler workaround no longer needed

Followup on #94 now that Intel 18+ is required.
2020-10-12 16:31:44 -04:00
Henry Schreiner
fecef38864
refactor: simpler followup to #2569 (#2572) 2020-10-09 17:12:05 -04:00
Henry Schreiner
f385eccdb7 chore: bump to 2.6.0rc1 2020-10-09 16:41:42 -04:00
Ahmed Sobhy
8d8d48c528
fix: do not use abi::__forced_unwind with libc++, even with gcc instead of clang (#2569)
* 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>
2020-10-09 16:10:23 -04:00
Yannick Jadoul
0c5cc031ee
feat: deprecate public constructors of module_ class (#2552)
* 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_
2020-10-09 10:46:11 -04:00
Yannick Jadoul
71aea49b8b
Check scope's __dict__ instead of using hasattr when registering classes and exceptions (#2335)
* 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
2020-10-09 01:09:56 +02:00
Henry Schreiner
00edc3001b
fix: PYBIND11_OBJECT required pybind11 namespace (regression) (#2553)
* 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
2020-10-06 10:04:13 -04:00
Henry Schreiner
9a0c96dd4c
feat: py::prepend tag (#1131)
* feat: add a priority overload with py::prepend

* doc: fix wording as suggested by rwgk

* feat: add get_pointer

* refactor: is_prepended -> prepend (internal)

* docs: suggestion from @wjakob

* tests: add test covering get_pointer/set_pointer
2020-10-05 22:36:33 -04:00
Yannick Jadoul
f537093a2f
Fail on passing py::object with wrong Python type to py::object subclass using PYBIND11_OBJECT macro (#2349)
* 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
2020-10-05 22:48:54 +02:00
Yannick Jadoul
1411207711
chore: drop support for PyPy < 7.3.1 and clean up old PyPy workarounds (#2456)
* 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>
2020-10-05 10:43:27 -04:00
Fritz Reese
e8ad33bb30
Fix buffer_info for ctypes buffers (pybind#2502) (#2503)
* 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.
2020-10-03 23:09:14 +02:00
Henry Schreiner
6bcd220c8d
refactor: module -> module_ with typedef (#2544)
* WIP: module -> module_ without typedef

* refactor: allow py::module to work again
2020-10-03 13:38:03 -04:00
Hyrum Wright
961b2e6205
fix: ensure the GIL is held when copying a function. (#2545)
Co-authored-by: Hyrum Wright <hwright@google.com>
2020-10-02 17:00:45 -04:00
Yannick Jadoul
9796fe98fc
feat: vectorize functions with void return type (#1969)
* 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>
2020-10-02 15:30:34 -04:00
Yannick Jadoul
56784c4f42
Add unchecked_reference::operator() and operator[] to overload resolution of unchecked_mutable_reference (#2514) 2020-10-02 19:07:04 +02:00
Riyaz Haque
2b6b98e28f
Bugfix/Check actual value when deregistering pybind11 instance (#2252)
* 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>
2020-10-02 19:06:04 +02:00
Yannick Jadoul
07b069a55b
Unify Python 2 & 3 py::module constructor, and make contructor with pre-allocated PyModuleDef private (#2534) 2020-10-02 10:01:24 -04:00
Boris Staletic
5ebc78164d
Allow raw unions without base classes in is_accessible_base_of (#2320)
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2020-10-02 09:39:22 -04:00
Yannick Jadoul
c72708a746
Moving tp_class access, and consistent fully-qualified naming for PyPy, to detail::get_tp_name (#2520)
* Moving tp_class access, and consistent fully-qualified naming for PyPy, to detail::get_tp_name

* Change get_tp_name to get_fully_qualified_tp_name
2020-10-01 22:57:25 -04:00
Henry Schreiner
0fc5774c0c
fix: beta does not have a dot in front (#2539) 2020-09-30 16:32:19 -04:00
Henry Schreiner
2190246243 chore: bump to 2.6.0b1, beta release 2020-09-30 16:10:26 -04:00
Ralf W. Grosse-Kunstleve
d159a56338
static allocation for PyModuleDef, to avoid leak check errors. (#2413)
* 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
2020-09-26 22:55:11 -07:00
Henry Schreiner
3c7ef56bb6
fix: warning on latest AppleClang (#2522)
Fixed in #2510 but reintroduced on one line by #2126
2020-09-22 23:36:25 +02:00
David Vo
5e6ec49652
Add enum value to enum repr (#2126)
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.
2020-09-20 01:12:19 +02:00
Rickard Hallerbäck
5a8ec8e505
Include what is used in pybind11.h (#2499)
* Include what is used

* Separated the C++ standard library headers and the project headers

* Reordering includes
2020-09-19 20:25:46 +02:00
Henry Schreiner
d0ed035cc5
fix: AppleClang 12 warnings (#2510)
* fix: AppleClang 12 new warning

* Fix: AppleClang X.X.0 will not trigger this warning
2020-09-19 20:23:47 +02:00
Henry Fredrick Schreiner
11f756f5a9 fix: type bug intruduced in #2492
This now tests the old form too, and fixes the bug introduced.
2020-09-16 23:21:47 -04:00
Boris Staletic
d3c999c774
fix: rename pybind11::module to pybind11::module_ (#2489)
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.
2020-09-16 17:15:42 -04:00
Henry Schreiner
fd61f5038e
feat: setup.py redesign and helpers (#2433)
* 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
2020-09-16 17:13:41 -04:00
Henry Schreiner
41aa92601e
refactor: replace .get_type with type::handle_of (#2492)
* refactor: replace .get_type with type::handle_of

* refactor: use impl for handle_of

* fix: deprecate h.get_type()
2020-09-16 11:32:17 -04:00
Yannick Jadoul
16f199f8d9
Change base parameter type in register_exception and exception constructor from PyObject* to handle (#2467)
* Change base parameter type in register_exception and excepion constructor from PyObject* to handle

* Fix compilation error passing `handle` to `PyObject*`
2020-09-15 10:24:39 -04:00
Henry Schreiner
e7bafc8ec1 style: clang-tidy: default checks and fix bug in iostream deconstruction
```
/pybind11/include/pybind11/iostream.h:71:9: warning: Call to virtual method 'pythonbuf::sync' during destruction bypasses virtual dispatch [clang-analyzer-optin.cplusplus.VirtualCall]
        sync();
        ^
/pybind11/tests/test_iostream.cpp:72:5: note: Calling '~scoped_ostream_redirect'
    });
```
2020-09-15 09:56:59 -04:00
Henry Schreiner
4d78640830 style: clang-tidy: modernize-use-emplace 2020-09-15 09:56:59 -04:00
Henry Schreiner
ce88e940ce style: clang-tidy: modernize-use-auto 2020-09-15 09:56:59 -04:00
Henry Schreiner
b491b465c7 style: clang-tidy: modernize-use-equals-default 2020-09-15 09:56:59 -04:00
Henry Schreiner
b342c37388 style: clang-tidy: modernize-use-using 2020-09-15 09:56:59 -04:00
Henry Schreiner
96e6a8d554 style: clang-tidy: readability-container-size-empty 2020-09-15 09:56:59 -04:00
Henry Schreiner
5dfbe6f903 style: clang-tidy: modernize-use-override 2020-09-15 09:56:59 -04:00
Henry Schreiner
8dc31c7b29 style: clang-tidy: llvm-namespace-comment 2020-09-15 09:56:59 -04:00
Yannick Jadoul
d65e34d61d
Resolve empty statement warning when using PYBIND11_OVERLOAD_PURE_NAME and PYBIND11_OVERLOAD_PURE (#2325)
* 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
2020-09-15 14:56:20 +02:00
Yannick Jadoul
9df13835c8
Stop py::array_t arguments from accepting arrays that do not match the C- or F-contiguity flags (#2484)
* Stop py::array_t arguments from accepting arrays that do not match the C- or F-contiguity flags

* Add trivially-contiguous arrays to the tests
2020-09-15 14:50:51 +02:00
Henry Schreiner
f12ec00d70
feat: py::type::of<T>() and py::type::of(h) (#2364)
* 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
2020-09-14 18:06:26 -04:00
Boris Staletic
cc982ac1cd
fix: allow assignment of time points of resolutions other than that of a system clock (#2481) 2020-09-13 10:24:00 -04:00
andriish
38370a87f4
fix: support NVIDIA-PGI HPC SDK (#2475)
* 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>
2020-09-11 22:06:52 -04:00
Yannick Jadoul
fe9ee86ba8
Add check if str(handle) correctly converted the object, and throw py::error_already_set if not (bis) (#2477)
* 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
2020-09-11 19:53:04 +02:00
Ciro Santilli
b47efd35fb
Use defined for some preprocessor variables that might be undefined (#2476)
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.
2020-09-10 13:58:26 -04:00
Henry Schreiner
621906b3e7
fix: support nvcc and test (#2461)
* fix: support nvcc and test

* fixup! fix: support nvcc and test

* docs: mention what compilers fail

* fix: much simpler logic

* refactor: slightly faster / clearer
2020-09-10 11:49:26 -04:00
Henry Schreiner
0dbda6e80b
feat: py::pos_only (#2459)
* feat: py::pos_only

* fix: review points from @YannickJadoul

* fix: review points from @bstaletic

* refactor: kwonly -> kw_only
2020-09-04 20:02:05 -04:00
Ralf W. Grosse-Kunstleve
3c061f2168 Fixing pybind11::bytes() ambiguous conversion issue.
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.
```
2020-08-28 11:52:51 -07:00
Yannick Jadoul
6a192781fc
Fix bug roundtripping datetime.time objects after midnight in eastern hemisphere timezones (#2417) (#2438)
* Fix bug roundtripping datetime.time objects after midnight in eastern hemisphere timezones (#2417)

* tests: check more timezones

* Fix review remarks: remove useless comment and skip setting TZ environment variable on Windows
2020-08-28 15:21:43 +02:00
Dekken
1abc4a9de5
fix: doc typo, drop second use of 'without' (#2439) 2020-08-27 00:55:18 +02:00
Yannick Jadoul
a2bb297b32
Throw exception on returning a unique_ptr or shared_ptr nullptr (or any other holder type) from py::init, rather than crashing (#2430) 2020-08-25 18:51:06 +02:00
Henry Schreiner
56df3c4649
fix: a couple more places where pybind11 is missing 11 (#2421) 2020-08-21 15:27:21 -04:00
Henry Schreiner
cf0a64596e
fix: throwing repr caused a segfault (#2389)
* fix: throwing repr caused a segfault

* fixup! ci: include Python 3.9 RC1 (#2387)
2020-08-18 07:14:34 -04:00
James R. Barlow
3618bea2aa Add and document py::error_already_set::discard_as_unraisable()
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.
2020-08-16 10:05:03 -07:00
Michael Goulding
fb042d692f
Fix warning C26817 on copying in for (auto vh : value_and_holder(...)) (#2382)
* 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>
2020-08-14 18:15:50 +02:00
Henry Schreiner
2e2de8c87a
fix: add missing signature (#2363)
* fix: add missing signature

* fix: add to array_t too
2020-08-13 20:13:16 -04:00
marc-chiesa
830adda850
Modified Vector STL bind initialization from a buffer type with optimization for simple arrays (#2298)
* 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
2020-08-13 22:47:23 +02:00
Yannick Jadoul
3e448c0b5e
Enable py::ellipsis on Python 2 (#2360)
* Enable py::ellipsis on Python 2

* Enable py::ellipsis tests on Python 2 and mention `Ellipsis` in the docs
2020-08-04 14:45:55 +02:00
jbarlow83
4d90f1a199
Add error_scope to py::class_::dealloc() to protect destructor calls (#2342)
Fixes issue #1878
2020-07-31 17:46:12 -07:00
Henry Schreiner
1651c32492 update: address review points 2020-07-30 20:27:55 -04:00
Henry Schreiner
6ec1775fff feat: drop CMake 3.6 and below, modernize CMake
fix: include PYTHON_IS_DEBUG
2020-07-30 20:27:55 -04:00
Marcin Wojdyr
8e40e389fd
cast pointer to std::tuple and std::pair (#2334) 2020-07-28 21:44:19 +02:00
Sergei Izmailov
7b067cc387
Set __hash__ to None for types that defines __eq__, but not __hash__ (#2291)
fixes #2191
2020-07-27 01:44:25 +02:00
Henry Schreiner
4470671796 fix: too many braces on clang 3.6 2020-07-26 09:25:27 -04:00
Henry Schreiner
e428a7f6b8 ci: fix clang warnings 2020-07-26 09:25:27 -04:00
Boris Staletic
2819ce64a4
Avoid attr("__repr__") in initialize_generic (#2317)
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
2020-07-24 18:43:59 +02:00
Kota Yamaguchi
e248869893
Fix undefined memoryview format (#2223)
* 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
2020-07-15 08:50:43 -07:00
Boris Staletic
aa982e131d
Small fixes in numpy.h (#2293)
- `PyArray_NewFromDescr_` should have been using `Py_intptr_t const *`
  - 18a6e3e505/numpy/core/src/multiarray/ctors.h (L5-L8)
- `PyArray_GetArrayParamsFromObject_` should be using `NPY_BOOL`
  - 18a6e3e505/numpy/core/src/multiarray/ctors.c (L1350-L1355)
  - https://docs.scipy.org/doc/numpy-1.13.0/reference/c-api.dtype.html#c.npy_bool
- `PyArray_DescrNewFromType` is at offset 96
  - 36e017194c/numpy/core/code_generators/numpy_api.py (L141)
- `array_t` constructor that takes a size and a pointer should take `ssize_t`.
  - Fixes #1599
2020-07-12 16:45:13 +02:00
Florian Apolloner
fe1392d089
Silence Clang 10 compiler warnings. Fixes #2225. (#2294) 2020-07-12 14:16:19 +02:00
Boris Staletic
8b9eb964d9
Check for NULL in raw_str on Python3 (#2290) 2020-07-11 17:20:22 +02:00
Boris Staletic
b2f52225fa
Rename embedded_module object's name (#2282)
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
2020-07-10 16:31:03 +02:00
Yannick Jadoul
f980d76d38
Change NAMESPACE_* macros into PYBIND11_NAMESPACE_* (#2283)
* 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>
2020-07-08 18:14:41 -04:00
Isuru Fernando
0d70f0e18e
PyPy3 support (#2146)
* 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>
2020-07-07 15:58:16 +02:00
Robert Haschke
f2226aefe0
Allow perfect forwarding of method args (#2048) 2020-07-07 15:56:07 +02:00
Dustin Spicuzza
1b0bf352fa
Throw TypeError when subclasses forget to call __init__ (#2152)
- Fixes #2103
2020-07-07 12:04:06 +02:00
Yannick Jadoul
d54d6d8c61
Adding pybind11::cast overload for rvalue references (#1260)
* Adding pybind11::cast overload for rvalue references
2020-07-01 01:53:09 +02:00
Boris Staletic
ae2ee2a4a5 Avoid using deprecated API in python 3.9
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.
2020-06-30 23:50:23 +02:00
fatvlady
f99ff736c2 Add additional check to be more compliant with other casters 2020-06-29 21:01:20 +02:00
fatvlady
556277d689 Fix optional dereference type deduction 2020-06-29 21:01:20 +02:00
Ashley Whetter
8e85fadff2 Render py::none as None in docstrings
Closes #2270
2020-06-29 11:48:44 +02:00
methylDragon
d96c34516d Fix docs typo 2020-06-15 23:19:19 +02:00
Sergei Izmailov
4f1531c454 Render py::int_ as int in docstrings 2020-06-10 13:36:31 +02:00
Sergei Izmailov
90d99b56a0 Render pybind11::array as numpy.ndarray in docstrings 2020-06-10 13:36:31 +02:00
Sergei Izmailov
57070fb0a0 Render py::iterator/py::iterable as Iterator/Iterable in docstrings 2020-06-10 13:36:31 +02:00
Sergei Izmailov
22b2504080 Render full numpy numeric names (e.g. numpy.int32) 2020-06-10 13:36:31 +02:00
Clemens Sielaff
63df87fa49
Add lvalue ref-qualified cpp_function constructors (#2213)
* added overload for l-value ref-qualified methods

* Added test.
Before, the code would have failed to build.
2020-06-10 13:35:10 +02:00
Thomas Köppe
1e14930dfc [common.h] Mark another entry point as "unused".
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.
2020-06-10 13:27:10 +02:00
Simeon Ehrig
c776e9ef93 Fix compiler error with MSVC 17 and CUDA 10.2 2020-06-09 01:57:57 +02:00
Thomas Köppe
eeb1044818 [common.h] Mark entry point 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.)
2020-06-05 01:53:26 +02:00
Andrey Dorozhkin
1817d2116a Disable defining (v)snprintf as macro in modern Visual Studio 2020-06-05 01:49:13 +02:00
Eric Cousineau
4e3d9fea74 operators: Explicitly expose py::hash(py::self)
Add warnings about extending STL
2020-05-31 07:03:01 +02:00
Andrew J. Hesford
a3118130c6
pytypes.h: fix docs generation (#2220) 2020-05-31 06:59:50 +02:00
Nicholas Musolino
02c83dba0f Propagate exceptions in sequence::size() (#2076) 2020-04-26 18:40:52 +02:00
Yannick Jadoul
805c5862b6 Adding method names to cpp_function constructor calls in enum_base 2020-04-26 18:27:18 +02:00
Sebastian Koslowski
a86ac538f5 rename args_kw_only to kwonly 2020-04-26 18:07:51 +02:00
Jason Rhinelander
be0d804523 Support keyword-only arguments
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).
2020-04-26 18:07:51 +02:00
peter
03f9e4a8ec Fix compilation with clang-cl 2020-04-26 09:47:34 +02:00
Dustin Spicuzza
0dfffcf257 Add is_final to disallow inheritance from Python
- Not currently supported on PyPy
2020-04-26 09:46:44 +02:00
David Stone
5088364b96 Declare operator== and operator!= member functions const. 2020-04-26 09:20:22 +02:00
Ralf W. Grosse-Kunstleve
4697149d19 Allows users to specialize polymorphic_type_hook with std::enable_if.
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.
2020-04-14 17:48:43 +02:00
Wenzel Jakob
0234871649 begin working on next version 2020-03-31 13:09:41 +02:00
Wenzel Jakob
3b1dbebabc v2.5.0 release 2020-03-31 13:00:39 +02:00
fwjavox
e97c735fc4 stl_bind: add binding for std::vector::clear (#2074) 2020-01-17 01:16:56 +01:00
Robert Haschke
370a2ae2b3 Declare call_impl() as && (#2057) 2020-01-05 15:49:24 +01:00
Wenzel Jakob
bf2b031449 Handle cases where binding code immediately throws py::error_already_set
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.
2020-01-02 22:18:03 +01:00
Wenzel Jakob
4c206e8c79 bindings for import_error exception 2020-01-02 22:17:20 +01:00
Wenzel Jakob
f9f3bd711f
Use C++17 fold expressions when casting tuples and argument lists (#2043)
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.
2019-12-30 01:26:32 +01:00
Vemund Handeland
6e39b765b2 Add C++20 char8_t/u8string support (#2026)
* Fix test build in C++20

* Add C++20 char8_t/u8string support
2019-12-19 12:16:24 +01:00
JGamache-autodesk
37d04abdee Fixes #1295: Handle debug interpreter (#2025)
If a debug interpreter is detected, we allow linking with
pythonXX_d.lib under windows.
2019-12-19 12:15:42 +01:00
Wenzel Jakob
b4e5d582cb undo #define copysign in pyconfig.h 2019-12-13 11:11:33 +01:00
Boris Staletic
1376eb0e51 Free tstate on python 3.7+ on finalize_interpreter (#2020) 2019-12-12 15:55:54 +01:00
Wenzel Jakob
fb910ae92b Revert "Fix a memory leak when creating Python3 modules. (#2019)"
This reverts commit 819802da99.
2019-12-11 21:26:46 +01:00
Nils Berg
819802da99 Fix a memory leak when creating Python3 modules. (#2019) 2019-12-11 16:01:45 +01:00
Wenzel Jakob
a60648223d Revert "numpy.h: minor preprocessor fix suggested by @chaekwan"
This reverts commit 61e4f11823.
2019-11-28 08:07:32 +01:00
Wenzel Jakob
61e4f11823 numpy.h: minor preprocessor fix suggested by @chaekwan 2019-11-28 07:42:34 +01:00
Sebastian Koslowski
dc65d66171 support for readonly buffers (#863) (#1466) 2019-11-24 08:33:05 +01:00
Francesco Biscani
bd24155b8b Aligned allocation fix for clang-cl (#1988) 2019-11-16 01:18:24 +01:00
Francesco Biscani
deb3cb238a Add exception translation for std::overflow_error. (#1977) 2019-11-14 08:56:58 +01:00
Yannick Jadoul
55ff464233 Fixing SystemError when nb_bool/nb_nonzero sets a Python exception in type_caster<bool>::load (#1976) 2019-11-14 08:56:22 +01:00
Sebastian Gsänger
a83d69e78f test pair-copyability on C++17 upwards (#1886)
* 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
2019-10-31 12:38:24 +01:00
Hans Dembinski
bdf6a5e870 Report type names in return value policy-related cast exceptions (#1965) 2019-10-23 13:19:58 +02:00
Jeremy Nimmer
759221f5c5 Obey __cpp_sized_deallocation and __cpp_aligned_new
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.
2019-10-22 11:02:11 +02:00
Riccardo Bertossa
6c29cbf88d misleading comment corrected (strides in buffer_info is bytes and not number of entries) (#1958) 2019-10-18 17:55:17 +02:00
nicolov
de5a29c0d4 Fix build with -Wmissing-prototypes (#1954)
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.
```
2019-10-17 10:43:33 +02:00
Wenzel Jakob
dfde1554ea begin working on next version 2019-10-15 01:58:43 +02:00
Wenzel Jakob
80d452484c v2.4.3 release 2019-10-15 01:57:24 +02:00
Sergei Izmailov
6cb584e9de Adapt to python3.8 C API change (#1950)
* 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
2019-10-08 18:25:09 +02:00
Wenzel Jakob
34c2281e31 begin working on next version 2019-09-21 20:23:01 +02:00
Wenzel Jakob
7ec2ddfc95 v2.4.2 release 2019-09-21 20:20:26 +02:00
Wenzel Jakob
7f5dad7d5f Remove usage of C++14 constructs (fixes #1929) 2019-09-21 19:03:14 +02:00
Wenzel Jakob
f3109d8419 future-proof Python version check from commit 31680e6 (@lgritz) 2019-09-21 18:09:35 +02:00
Wenzel Jakob
82cf793588 begin working on next version 2019-09-20 11:12:22 +02:00
Wenzel Jakob
e44fcc3c15 v2.4.1 release 2019-09-20 11:10:49 +02:00
Wenzel Jakob
31680e6f9c Implicit conversion from enum to int for Python 3.8 (fix by @sizmailov) 2019-09-20 11:06:10 +02:00
Wenzel Jakob
e825205ac6 begin working on v2.4.1 2019-09-19 23:18:04 +02:00
Wenzel Jakob
00a0aa9929 v2.4.0 release 2019-09-19 23:06:22 +02:00
Samuel Debionne
6ca312b3bc Avoid infinite recursion in is_copy_constructible (#1910) 2019-09-19 21:24:05 +02:00
Wenzel Jakob
c9f5a464bc pybind11 internals: separate different compilers 2019-09-19 21:12:14 +02:00
Sergei Izmailov
09f0829401 Avoid conversion to int_ rhs argument of enum eq/ne (#1912)
* 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
2019-09-19 18:23:27 +02:00
Lori A. Burns
f6c4c1047a restores __invert__ to arithmetic-enabled enum, fixes #1907 (#1909) 2019-09-04 22:16:21 +02:00
Stephen Larew
5b4751af26 Add const to buffer:request() (#1890) 2019-08-27 17:05:47 +02:00
kingofpayne
12e8774bc9 Added support for list insertion. (#1888) 2019-08-19 23:00:36 +02:00
Andre Schmeißer
19189b4c2c Make overload_cast_impl available in C++11 mode. (#1581)
* 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
2019-08-19 12:54:33 +02:00
Vladimír Vondruš
04c8f4b56e Expose BufferError among other pybind11 exceptions. (#1852) 2019-08-19 12:48:03 +02:00
Sergei Lebedev
046267c629 Added .empty() to all collection types (#1887) 2019-08-16 23:43:08 +02:00
Sergei Lebedev
08b0bda4bc Added set::contains and generalized dict::contains (#1884)
Dynamically resolving __contains__ on each call is wasteful since set
has a public PySet_Contains function.
2019-08-16 21:32:27 +02:00
Vladimír Vondruš
5b0ea77c62 Fix -Wmissing-prototypes warning on Clang. (#1863)
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.
2019-08-16 08:52:13 +02:00
ali-beep
5ef13eb680 Add negative indexing support to stl_bind. (#1882) 2019-08-15 19:41:11 +02:00
Borja Zarco
b2fdfd1228 Avoid use of lambda to work around a clang bug. (#1883)
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
2019-08-15 13:42:43 +02:00
Saran Tunyasuvunakool
bdf1a2cc34 In internals.h, only look at _DEBUG when compiling with MSVC. (#1855)
* In internals.h, only look at _DEBUG when compiling with MSVC.

(_DEBUG is a MSVC-specific macro.)
2019-08-13 22:00:47 +02:00
Pauli Virtanen
c9d32a81f4 numpy: fix refcount leak to dtype singleton (#1860)
PyArray_DescrFromType returns a new reference, not borrowed one
2019-07-27 11:35:32 +02:00
Eric Cousineau
4a3464fd88 numpy: Provide concrete size aliases
Test for dtype checks now succeed without warnings
2019-07-23 13:17:20 +02:00
phil-zxx
c6b699d9c2 Added ability to convert from datetime.date to system_clock::time_point (#1848)
* Added ability to convert from Python datetime.date and datetime.time to C++ system_clock::time_point
2019-07-19 11:28:48 +02:00
Jeremy Maitin-Shepard
a3f4a0e8ab Add support for __await__, __aiter__, and __anext__ protocols (#1842) 2019-07-18 09:02:35 +02:00
Nathan
9b3fb05326 Allow Windows.h min/max to coexist with pybind11 (#1847)
* Protect std::min/max functions from windows.h min/max
Removed check for windows min/max
2019-07-18 09:01:50 +02:00
Wenzel Jakob
b2c4ff6052 renamed local gil_scoped_acquire to gil_scoped_acquire_local to avoid ambiguity 2019-07-15 17:29:13 +02:00
Saran Tunyasuvunakool
b60fd233fa Make sure detail::get_internals acquires the GIL before making Python calls. (#1836)
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
2019-07-15 16:47:02 +02:00
Thomas Peters
dffe869dba quiet clang warning by adding default move ctor (#1821) 2019-07-15 16:16:14 +02:00
Igor Socec
a301c5add8 Dtype field ordering for NumPy 1.14 (#1837)
* 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
2019-07-15 13:31:03 +02:00
Toru Niina
74d335a535 Replace a usage of C++14 language features with C++11 code (#1833) 2019-07-10 10:13:56 +02:00
Wenzel Jakob
8b90b1da62 error_already_set: acquire GIL one line earlier (fixes #1779) 2019-07-06 14:52:32 +02:00
Wenzel Jakob
a1b71df137 fix issue #1804 (warning about redefined macros) 2019-06-19 10:48:42 +02:00
Alexander Gagarin
b3bf248eec Fix casting of time points with non-system-clock duration with VS (#1748)
* 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
2019-06-13 09:17:10 +02:00
Wenzel Jakob
64f2a5f8e6 begin work on v2.3.1 2019-06-12 21:03:40 +02:00
sizmailov
21c3911bd3 add signed overload for py::slice::compute 2019-06-11 23:28:58 +02:00
Chris Rusby
22859bb8fc Support more natural syntax for vector extend 2019-06-11 23:28:58 +02:00
Roland Dreier
1aa8dd1745 Fix assertion failure for unions (#1685) (#1709)
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.
2019-06-11 23:28:58 +02:00
Alexander Gagarin
0071a3feb0 Fix async Python functors invoking from multiple C++ threads (#1587) (#1595)
* 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
2019-06-11 23:28:58 +02:00
Henry Schreiner
047ce8c452 Fix iostream when used with nogil (#1368) 2019-06-11 23:28:58 +02:00
Omar Awile
95f750a87d Add optional buffer size to pythonbuf::d_buffer constructor (#1687)
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).
2019-06-11 23:28:58 +02:00
Axel Huebl
38f408fccd value_and_holder: uninit members (#1660)
fix some uninitialized members in `value_and_holder` for
some of the constructurs.

Found with coverity in a downstream project.
2019-06-11 23:28:58 +02:00
Jeff VanOss
77ef03d5b1 compile time check that properties have no py:arg values (#1524) 2019-06-11 14:25:35 +02:00
Yannick Jadoul
d23c821b20 Make static member functions, added with def_static, staticmethod descriptor instances (#1732) 2019-06-11 10:59:57 +02:00
Axel Huebl
a2cdd0b915 dict_readonly: member init (#1661)
fix missing member initialization in pytypes: read-only dict.

Found with coverity in a downstream project.
2019-06-10 22:19:41 +02:00
Axel Huebl
1c627c9ec0 pybind11_getbuffer: useless safe nullptr check (#1664)
Alternative implementation for #1657: if
we know that `obj` is never a `nullptr` [1], we should
not `nullptr`-check it *after* already dereferencing it.

[1] https://github.com/pybind/pybind11/pull/1657#issuecomment-452090058
2019-06-10 22:18:11 +02:00
Jeffrey Quesnelle
f93cd0aa72 PYBIND11_TLS_REPLACE_VALUE should use macro argument value in Python 3.7+ (#1683) 2019-06-10 22:13:35 +02:00
Ivor Wanders
2b045757b5 Improve documentation related to inheritance. (#1676)
* Adds section to the reference.
* Adds section to advanced classes page describing how to use `get_overload`.
2019-06-10 22:12:28 +02:00
Axel Huebl
9424d5d277 type_record: Uninit Member (#1658)
Fix an uninitialized member in `type_record`.

Found with coverity in a downstream project.
2019-06-10 22:02:40 +02:00
Jörg Kreuzberger
69dc380c0d #1208 Handle forced unwind exception (e.g. during pthread termination)
* #1208 Bugfix thread kill wihile running pybind11 module

* #1208 Bugfix missing space after catch
2019-06-10 22:00:55 +02:00
Steven Johnson
4ddf7c402d Add missing includes for better Bazel compatibility (#1255)
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.
2019-06-10 21:54:56 +02:00
Blake Thompson
30c0352348 Added __contains__ to stl bindings for maps (#1767)
* Added __contains__ to stl bindings for maps
2019-06-10 21:01:11 +02:00
Yannick Jadoul
97784dad3e [BUGFIX] Fixing pybind11::error_already_set.matches to also work with exception subclasses (#1715)
* 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
2019-05-12 23:35:49 +02:00
martinRenou
35045eeef8 Add getters for exception type, value and traceback (#1641) 2019-05-03 14:32:28 +02:00
Henry Schreiner
9bb3313162 Fixing warnings about conversions in GCC 7+ (#1753) 2019-04-07 10:38:10 +02:00
Henry Schreiner
ae951ca085 CI fixes (#1744)
* 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
2019-04-06 19:09:39 +02:00
Wenzel Jakob
ccbe68b084 added binding delattr() -> PyObject_DelAttr analogous to hasattr() 2019-02-04 16:24:07 +01:00
Boris Staletic
0ca6867e8e Avoid Visual Studio 2017 15.9.4 ICE 2019-01-03 12:05:01 +01:00
Borja Zarco
e2b884c33b Use PyGILState_GetThisThreadState when using gil_scoped_acquire. (#1211)
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).
2018-12-01 22:47:40 +09:00
Baljak
81da9888c7 Fix Intel C++ compiler warning on Windows (#1608) 2018-11-20 23:22:02 +01:00
voxmea
17983e7425 Adds type_caster support for std::deque. (#1609)
* 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.
2018-11-16 06:45:19 +01:00
Karl Haubenwallner
e9d6e87949 Added a debug flag to the PYBIND11_INTERNALS_VERSION (#1549) 2018-11-11 20:49:33 +01:00
Trevor Laughlin
63c2a972fe Enable unique_ptr holder with mixed Deleters between base and derived types (#1353)
* 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
2018-11-11 19:36:55 +01:00
Wenzel Jakob
cea42467b0
fix py::cast<void *> (#1605)
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.
2018-11-11 19:32:09 +01:00
Wenzel Jakob
e2eca4f8f8
Support C++17 aligned new statement (#1582)
* 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.
2018-11-09 20:14:53 +01:00
Wenzel Jakob
adc2cdd5c4
fixed regression in STL type caster RVPs (fixes #1561) (#1603) 2018-11-09 20:12:46 +01:00
Wenzel Jakob
9f73060cc7
std::array<> caster: support arbitrary sequences (#1602)
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).
2018-11-09 12:32:48 +01:00
Michał Wawrzyniec Urbańczyk
978d439e92 Add PYBIND11_ prefix to the THROW macro to prevent name collisions. (#1578) 2018-11-03 13:20:08 +01:00
Josh Kelley
741576dd11 Update documentation for initialize_interpreter (#1584)
Add a detailed link to Python 3 documentation.  Add a caveat about
the program terminating if initializing the interpreter fails.
2018-11-01 02:10:11 +01:00
Tarcísio Fischer
54eb8193e5 Fix scoped enums comparison for equal/not equal cases (#1339) (#1571) 2018-10-24 11:18:58 +02:00
Allan Leal
e76dff7751 Fix for Issue #1258 (#1298)
* 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
2018-10-11 10:28:12 +02:00
Rune Paamand
73634b6db7 Update iostream.h: Changed a local varname 'self' to 'self_' (#1535)
* Update iostream.h: Changed a local varname 'self' to 'self_'

Avoiding conflicts in namespace pybind11::self.
https://github.com/pybind/pybind11/issues/1531
2018-09-27 16:26:42 +02:00
oremanj
e7761e3383 Fix potential crash when calling an overloaded function (#1327)
* 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
2018-09-25 23:55:18 +02:00
Wenzel Jakob
c8e9f3ccad quench __setstate__ warnings (fixes #1522) 2018-09-14 12:07:47 +02:00
Wenzel Jakob
f4245181ae enum_: move most functionality to a non-template implementation
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.
2018-09-11 22:08:26 +02:00
Wenzel Jakob
b4b2292488 relax operator[] for tuples, lists, and sequences
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.
2018-09-11 22:08:26 +02:00
Wenzel Jakob
067100201f object_api: support the number protocol
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.
2018-09-11 22:08:26 +02:00
Krzysztof Fornalczyk
5c8746ff13 check for already existing enum value added; added test (#1453)
* 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
2018-09-11 10:59:56 +02:00
Wenzel Jakob
44e39e0de7
fix regression reported by @cyfdecyf in #1454 (#1517) 2018-09-11 09:32:45 +02:00
Michael Goulding
77374a7e5f VS 15.8.0 Preview 4.0 has a bug with alias templates (#1462)
* VS 15.8.0 Preview 4.0 has a bug with alias templates
2018-09-08 16:25:11 +02:00
Justin Bassett
2cbafb057f fix detail::pythonbuf::overflow()'s return value to return not_eof(c) (#1479) 2018-08-29 11:48:30 +02:00
Henry Schreiner
3789b4f9fd Update C++ macros for C++17 and MSVC Z mode (#1347) 2018-08-29 00:07:35 +02:00
Matthias Geier
7bb1da969a fix copy-paste error: non-const -> const 2018-08-28 23:23:13 +02:00
Wenzel Jakob
d4b37a284a added py::ellipsis() method for slicing of multidimensional NumPy arrays
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)];
2018-08-28 23:22:55 +02:00
Wenzel Jakob
cbd16a8247
stl.h: propagate return value policies to type-specific casters (#1455)
* 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.
2018-07-17 16:56:26 +02:00
Yannick Jadoul
b4719a60d3 Switching deprecated Thread Local Storage (TLS) usage in Python 3.7 to Thread Specific Storage (TSS) (#1454)
* 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
2018-07-17 16:55:52 +02:00
Dennis Luxen
221fb1e11e Untangle cast logic to not implicitly require castability (#1442)
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.
2018-07-17 10:48:51 -03:00
Antony Lee
baf6b99004 Silence GCC8's -Wcast-function-type. (#1396)
* Silence GCC8's -Wcast-function-type.

See https://bugs.python.org/issue33012 and PRs linked therein.
2018-06-24 15:38:09 +02:00
Khachajantc Michael
e3cb2a674a Use std::addressof to obtain holder address instead of operator& 2018-06-23 21:29:54 -03:00
Antony Lee
58e551cc73 Properly report exceptions thrown during module initialization.
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.
2018-06-15 10:56:50 -03:00
Naotoshi Seo
5ef1af138d Fix SEGV to create empty shaped numpy array (#1371)
Fix a segfault when creating a 0-dimension, c-strides array.
2018-05-06 10:59:25 -03:00
luzpaz
4b874616b2 Misc. typos (#1384)
Found via `codespell`
2018-05-06 10:54:10 -03:00
Lori A. Burns
bdbe8d0bde Enforces intel icpc >= 2017, fixes #1121 (#1363) 2018-04-29 13:48:25 +02:00
Wenzel Jakob
ed67005583
Minor fix for MSVC warning CS4459 (#1374)
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'
2018-04-22 14:04:31 +02:00
oremanj
fd9bc8f54d Add basic support for tag-based static polymorphism (#1326)
* 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.
2018-04-14 02:13:10 +02:00
Boris Staletic
289e5d9cc2 Implement an enum_ property "name"
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.
2018-04-07 19:11:35 -03:00
Jason Rhinelander
6862cb9b35 Add workaround for clang 3.3/3.4
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
2018-04-05 12:01:39 -03:00
Jason Rhinelander
6d0b4708c6 Reimplement version check and combine init macros
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.
2018-03-11 11:10:06 -03:00
Jason Rhinelander
9f41c8eade Fix class name in overload failure message 2018-03-10 14:24:23 -04:00
Jason Rhinelander
e88656ab45 Improve macro type handling for types with commas
- 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.
2018-03-10 14:24:23 -04:00
Wenzel Jakob
ff6bd092d4
Fix pybind11 interoperability with Clang trunk (#1269) 2018-02-06 15:40:50 +01:00
Jason Rhinelander
add56ccdca MSVC workaround for broken using detail::_ warning 2018-01-12 12:37:54 -04:00
Jason Rhinelander
657a51e889 Remove unnecessary detail::
This function already has a `using namespace detail`, so all the
`detail::` qualifications are not needed.
2018-01-12 12:06:46 -04:00
Jason Rhinelander
adbc8111bc Use stricter brace initialization
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).
2018-01-12 09:29:57 -04:00
Jason Rhinelander
326deef2ae
Fix segfault when reloading interpreter with external modules (#1092)
* 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).
2018-01-11 19:46:10 -04:00
Jeff VanOss
05d379a9aa fix return from std::map bindings to __delitem__ (#1229)
Fix return from `std::map` bindings to `__delitem__`: we should be returning `void`, not an iterator.

Also adds a test for map item deletion.
2018-01-11 19:43:37 -04:00