Commit Graph

546 Commits

Author SHA1 Message Date
Henry Schreiner e2a96890e1 format: add cmake-format to pre-commit 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
Henry Schreiner c51b3f436d ci: change caching 2020-07-27 22:12:19 -04:00
Henry Schreiner ff39ad3f31 ci: include scipy for tests 2020-07-27 22:12:19 -04:00
Henry Schreiner 1b880dfd5a ci: download EIGEN 2020-07-27 22:12:19 -04: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 aab701399a ci: cache, build wheels on macOS PyPy3 2020-07-26 09:25:27 -04:00
Henry Schreiner 5927c5819f chore: update Catch 2020-07-26 09:25:27 -04:00
Henry Schreiner 1f53c373e4 fix: C++17 mode on Clang may error 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
Henry Schreiner b16347e51d ci: enable GHA testing
Adds requirements file too.
2020-07-23 17:42:53 -04:00
Henry Schreiner a59c6de821 test: allow MSVC/Xcode to run the embed test 2020-07-23 17:42:53 -04:00
Henry Schreiner 49007b7ff3 test: fix warning/error on Python 2 in 14/17 mode 2020-07-23 17:42:53 -04:00
Henry Schreiner 3d20b73e87 test: pass through C++ std for cmake test 2020-07-23 17:42:53 -04:00
Henry Schreiner ef057f12b6 test: support pypy2 7.3 2020-07-23 17:42:53 -04:00
Ralf W. Grosse-Kunstleve 96c6763613
test_builtin_casters.py test_string_view: Python 2 c++17, c++2a compatibility. (#2314)
Tested with 2.7.18rc1, built with Py_UNICODE_SIZE 4.
Change also tested with Python 3.8.
2020-07-22 12:05:16 -07:00
Henry Schreiner d8c7ee00a6
ci: GHA basic format & pre-commit (#2309) 2020-07-20 13:35:21 -04: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
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
B Krishna Chaitanya 714424387f Refactor: Extract Custom Type Casts related tests 2020-07-01 00:07:49 +02:00
fatvlady 8c06b95492 Fix compile error on GCC4.8 2020-06-29 21:01:20 +02:00
fatvlady a3daf87d45 Add failing optional test 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
Sergei Izmailov ab323e04f3 Test py::iterable/py::iterator representation in docstrings 2020-06-10 13:36:31 +02:00
Sergei Izmailov 4f1531c454 Render `py::int_` as `int` 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
Eric Cousineau 4e3d9fea74 operators: Explicitly expose `py::hash(py::self)`
Add warnings about extending STL
2020-05-31 07:03:01 +02:00
Eric Cousineau 5309573005 operators: Move hash check to before mutations, tweak whitespace 2020-05-31 07:03:01 +02:00
Eric Cousineau 2c30e0a118
cmake: Expose `PYBIND11_TEST_OVERRIDE` (#2218)
Primarily for the ccmake curses GUI
2020-05-31 07:00:55 +02:00
Henry Schreiner a38e5331d7
Fix CI, prepare test on Python 3.9 beta (#2233)
* Test on Python 3.9 beta
* Pin Sphinx
* Newer version of PyPy
2020-05-31 06:29:30 +02:00
Nicholas Musolino 02c83dba0f Propagate exceptions in sequence::size() (#2076) 2020-04-26 18:40:52 +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
Dustin Spicuzza 0dfffcf257 Add is_final to disallow inheritance from Python
- Not currently supported on PyPy
2020-04-26 09:46:44 +02:00
Ralf W. Grosse-Kunstleve f6e543b15e Adding a default virtual destructor to Animal type in test_tagbased_polymorphic.cpp.
With this change, and cast.h as-is in master, test_tagbased_polymorphic.cpp fails to compile with the error message below.
With the cast.h change in pull/2016, building and testing succeeds.

cd pybind11/build/tests && /usr/bin/c++  -DPYBIND11_TEST_BOOST -DPYBIND11_TEST_EIGEN -Dpybind11_tests_EXPORTS -Ipybind11/include -I/usr/include/python3.7m -isystem /usr/include/eigen3  -Os -DNDEBUG -fPIC -fvisibility=hidden   -std=c++2a -flto -fno-fat-lto-objects -Wall -Wextra -Wconversion -Wcast-qual -Wdeprecated -o CMakeFiles/pybind11_tests.dir/test_tagbased_polymorphic.cpp.o -c pybind11/tests/test_tagbased_polymorphic.cpp
In file included from pybind11/include/pybind11/attr.h:13,
                 from pybind11/include/pybind11/pybind11.h:44,
                 from pybind11/tests/pybind11_tests.h:2,
                 from pybind11/tests/test_tagbased_polymorphic.cpp:10:
pybind11/include/pybind11/cast.h: In instantiation of ‘static std::pair<const void*, const pybind11::detail::type_info*> pybind11::detail::type_caster_base<type>::src_and_type(const itype*) [with type = Animal; pybind11::detail::type_caster_base<type>::itype = Animal]’:
pybind11/include/pybind11/cast.h:906:31:   required from ‘static pybind11::handle pybind11::detail::type_caster_base<type>::cast_holder(const itype*, const void*) [with type = Animal; pybind11::detail::type_caster_base<type>::itype = Animal]’
pybind11/include/pybind11/cast.h:1566:51:   required from ‘static pybind11::handle pybind11::detail::move_only_holder_caster<type, holder_type>::cast(holder_type&&, pybind11::return_value_policy, pybind11::handle) [with type = Animal; holder_type = std::unique_ptr<Animal>]’
pybind11/include/pybind11/stl.h:175:69:   required from ‘static pybind11::handle pybind11::detail::list_caster<Type, Value>::cast(T&&, pybind11::return_value_policy, pybind11::handle) [with T = std::vector<std::unique_ptr<Animal> >; Type = std::vector<std::unique_ptr<Animal> >; Value = std::unique_ptr<Animal>]’
pybind11/include/pybind11/pybind11.h:159:43:   required from ‘void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = std::vector<std::unique_ptr<Animal> > (*&)(); Return = std::vector<std::unique_ptr<Animal> >; Args = {}; Extra = {pybind11::name, pybind11::scope, pybind11::sibling}]’
pybind11/include/pybind11/pybind11.h:64:9:   required from ‘pybind11::cpp_function::cpp_function(Return (*)(Args ...), const Extra& ...) [with Return = std::vector<std::unique_ptr<Animal> >; Args = {}; Extra = {pybind11::name, pybind11::scope, pybind11::sibling}]’
pybind11/include/pybind11/pybind11.h:819:22:   required from ‘pybind11::module& pybind11::module::def(const char*, Func&&, const Extra& ...) [with Func = std::vector<std::unique_ptr<Animal> > (*)(); Extra = {}]’
pybind11/tests/test_tagbased_polymorphic.cpp:141:36:   required from here
pybind11/include/pybind11/cast.h:880:61: error: ambiguous template instantiation for ‘struct pybind11::polymorphic_type_hook<Animal, void>’
         const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
pybind11/include/pybind11/cast.h:844:8: note: candidates are: ‘template<class itype> struct pybind11::polymorphic_type_hook<itype, typename std::enable_if<std::is_polymorphic<_Tp>::value, void>::type> [with itype = Animal]’
 struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>>
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pybind11/tests/test_tagbased_polymorphic.cpp:115:12: note:                 ‘template<class itype> struct pybind11::polymorphic_type_hook<itype, typename std::enable_if<std::is_base_of<Animal, itype>::value, void>::type> [with itype = Animal]’
     struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_base_of<Animal, itype>::value>>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from pybind11/include/pybind11/attr.h:13,
                 from pybind11/include/pybind11/pybind11.h:44,
                 from pybind11/tests/pybind11_tests.h:2,
                 from pybind11/tests/test_tagbased_polymorphic.cpp:10:
pybind11/include/pybind11/cast.h:880:61: error: incomplete type ‘pybind11::polymorphic_type_hook<Animal, void>’ used in nested name specifier
         const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
2020-04-14 17:48:43 +02:00
fwjavox e97c735fc4 stl_bind: add binding for std::vector::clear (#2074) 2020-01-17 01:16:56 +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
Sebastian Koslowski dc65d66171 support for readonly buffers (#863) (#1466) 2019-11-24 08:33:05 +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
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 21d0eb460f Fix Python 3.8 test regression 2019-09-20 09:38:30 +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
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
ali-beep 5ef13eb680 Add negative indexing support to stl_bind. (#1882) 2019-08-15 19:41:11 +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 e9ca89f453 numpy: Add test for explicit dtype checks. At present, int64 + uint64 do not exactly match dtype(...).num 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
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
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
Wenzel Jakob 9fd4712121 fix test suite (pytest changes in ExceptionInfo class) 2019-07-06 17:35:31 +02:00
Ian Bell 502ffe50a9 Add docs and tests for unary op on class (#1814) 2019-06-22 12:07:41 +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 e11e71d85c Make compiler flags for -Werror specific to GNU, Clang, or Intel 2019-06-11 23:28:58 +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
Axel Huebl 000aabb2a7 Test: Numpy Scalar Creation (#1530)
I found that the numpy array tests already contained an empty-shaped
array test, but none with data in it.

Following PEP 3118, scalars have an empty shape and ndim 0. This
works already and is now also documented/covered by a test.
2019-06-11 14:00:05 +02:00
luzpaz 21bf16f5b8 misc. comment typo (#1629) 2019-06-10 21:56:38 +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
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 25abf7efba flake8 fixes 2019-02-04 17:09:47 +01:00
Guilhem Saurel 43a39bc7d8 ignore numpy.ufunc size warnings 2019-02-04 16:09:21 +01:00
Guilhem Saurel e7ef34f23f compatibility with pytest 4.0, fix #1670
Cf. https://docs.pytest.org/en/latest/deprecations.html#pytest-namespace
2019-02-04 16:09:21 +01:00
Yannick Jadoul 085a29436a Increasing timeout in test_gil_scoped.py to get AppVeyor to succeed 2019-01-03 22:43:52 +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
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
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
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
Jason Rhinelander 177713fa4e Fix gcc-8 compilation warning 2018-10-02 12:11:37 -03: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 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
Wenzel Jakob e0f3a766e9
Fixed flake8 error in test_iostream.py 2018-08-29 12:10:48 +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
Wenzel Jakob 885b5b905a Eigen test suite: don't create a np.matrix 2018-08-28 23:22:55 +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
Jason Rhinelander f7bc18f528 Fix compatibility with catch v2
Catch v2 changed the `run(...)` signature to take a `char *argv[]`,
arguing partly that technically a `char *argv[]` type is the correct
`main()` signature rather than `const char *argv[]`.

Dropping the `const` here doesn't appear to cause any problems with
catch v1 (tested against both the cmake-downloaded 1.9.3 and Debian's
1.12.1 package) so we can follow suit.
2018-07-19 16:12:39 -03: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
Khachajantc Michael e3cb2a674a Use std::addressof to obtain holder address instead of operator& 2018-06-23 21:29:54 -03:00
Jason Rhinelander e763f04689 Base class destructor should be virtual
Fixes #1401
2018-05-18 12:48:32 -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
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 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
luz.paz 13c08072dc Typo 2018-02-27 22:46:56 -04:00
Jason Rhinelander 431fc0e198 Fix numpy dtypes test on big-endian architectures
This fixes the test code on big-endian architectures: the array support
(PR #832) had hard-coded the little-endian '<' but we need to use '>' on
big-endian architectures.
2018-02-18 18:36:11 +01: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
luz.paz 28cb6764fc misc. typos
Found via `codespell`
2018-01-11 16:39:50 -04:00
Jason Rhinelander 88efb25145 Fixes for numpy 1.14.0 compatibility
- UPDATEIFCOPY is deprecated, replaced with similar (but not identical)
  WRITEBACKIFCOPY; trying to access the flag causes a deprecation
  warning under numpy 1.14, so just check the new flag there.
- Numpy `repr` formatting of floats changed in 1.14.0 to `[1., 2., 3.]`
  instead of the pre-1.14 `[ 1.,  2.,  3.]`.  Updated the tests to
  check for equality with the `repr(...)` value rather than the
  hard-coded (and now version-dependent) string representation.
2018-01-11 11:43:54 -04:00
Antony Lee 0826b3c106 Add spaces around "=" in signature repr.
PEP8 indicates (correctly, IMO) that when an annotation is present, the
signature should include spaces around the equal sign, i.e.

    def f(x: int = 1): ...

instead of

    def f(x: int=1): ...

(in the latter case the equal appears to bind to the type, not to the
argument).

pybind11 signatures always includes a type annotation so we can always
add the spaces.
2017-12-27 11:04:24 -04:00
Ivan Smirnov d1db2ccfdf Make register_dtype() accept any field containers (#1225)
* Make register_dtype() accept any field containers

* Add a test for programmatic dtype registration
2017-12-27 11:00:27 -04:00
Jason Rhinelander b48d4a01ca Added py::args ref counting tests 2017-12-23 18:53:26 -04:00
Jason Rhinelander 3be401f2a2 Silence new MSVC C++17 deprecation warnings
In the latest MSVC in C++17 mode including Eigen causes warnings:

    warning C4996: 'std::unary_negate<_Fn>': warning STL4008: std::not1(),
    std::not2(), std::unary_negate, and std::binary_negate are deprecated in
    C++17. They are superseded by std::not_fn(). You can define
    _SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING or
    _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have
    received this warning.

This disables 4996 for the Eigen includes.

Catch generates a similar warning for std::uncaught_exception, so
disable the warning there, too.

In both cases this is temporary; we can (and should) remove the warnings
disabling once new upstream versions of Eigen and Catch are available
that address the warning. (The Catch one, in particular, looks to be
fixed in upstream master, so will probably be fixed in the next (2.0.2)
release).
2017-12-23 09:00:45 -04:00
Henry Schreiner cf0d0f9d5a Matching Python 2 int behavior on Python 2 (#1186)
Pybind11's default conversion to int always produces a long on Python 2 (`int`s and `long`s were unified in Python 3). This patch fixes `int` handling to match Python 2 on Python 2; for short types (`size_t` or smaller), the number will be returned as an `int` if possible, otherwise `long`. Requires Python 2.5+.

This is needed for things like `sys.exit`, which refuse to accept a `long`.
2017-11-30 13:33:24 -04:00
Francesco Biscani ba33b2fc79 Add -Wdeprecated to test suite and fix associated warnings (#1191)
This commit turns on `-Wdeprecated` in the test suite and fixes several
associated deprecation warnings that show up as a result:

- in C++17 `static constexpr` members are implicitly inline; our
  redeclaration (needed for C++11/14) is deprecated in C++17.

- various test suite classes have destructors and rely on implicit copy
  constructors, but implicit copy constructor definitions when a
  user-declared destructor is present was deprecated in C++11.

- Eigen also has various implicit copy constructors, so just disable
  `-Wdeprecated` in `eigen.h`.
2017-11-22 17:37:41 -04:00
Wenzel Jakob 6d19036cb2
support docstrings in enum::value() (#1160) 2017-11-16 22:24:36 +01:00
Ted Drain 0a0758ce3a Added write only property functions for issue #1142 (#1144)
py::class_<T>'s `def_property` and `def_property_static` can now take a
`nullptr` as the getter to allow a write-only property to be established
(mirroring Python's `property()` built-in when `None` is given for the
getter).

This also updates properties to use the new nullptr constructor internally.
2017-11-07 12:35:27 -04:00
Jason Rhinelander 71178922fd
__qualname__ and nested class naming fixes (#1171)
A few fixes related to how we set `__qualname__` and how we show the
type name in function signatures:

- `__qualname__` isn't supposed to have the module name at the
beginning, but we've been putting it there.  This removes it, while
keeping the `Nested.Class` name chaining.

- print `__module__.__qualname__` rather than `type->tp_name`; the
latter doesn't work properly for nested classes, so we would get
`module.B` rather than `module.A.B` for a class `B` with parent `A`.
This also unifies the Python 3 and PyPy code.  Fixes #1166.

- This now sets a `__qualname__` attribute on the type (as would happen
in Python 3.3+) for Python <3.3, including PyPy.  While not particularly
important to have in earlier Python versions, it's useful for us to be
able to extracted the nested name, which is why `__qualname__` was
invented in the first place.

- Added tests for the above.
2017-11-07 12:33:05 -04:00
Unknown 0b3f44ebdf Trivial typos
Non-user facing. 
Found using `codespell -q 3`
2017-11-01 22:48:36 -03:00
Jason Rhinelander 5c7a290d37 Fix new flake8 E741 error from using `l` variable
The just-updated flake8 package hits a bunch of:

    E741 ambiguous variable name 'l'

warnings.  This commit renames them all from `l` to `lst` (they are all
list values) to avoid the error.
2017-10-25 08:18:21 -03:00
Jason Rhinelander 835fa9bcc6 Miscellaneous travis-ci updates/fixes
- For the debian/buster docker build (GCC 7/C++17) install and use the
  system `catch` package; this also renames "COMPILER_PACKAGES" to
  "EXTRA_PACKAGES" since it now contains a non-compiler package.

- Add a status message indicating the catch version being used for
  compiling the embedded tests

- Simplify some bash code by using VAR+=" foo" to append (rather than
  VAR="${VAR} foo"

- Fix CMAKE_INCLUDE_PATH appending: it was prepending the ':' but not
  the existing $CMAKE_INCLUDE_PATH value and so would end up with
  ":/eigen-path" if CMAKE_INCLUDE_PATH was already set.  (This wasn't
  bug that was actually noticed since currently nothing else sets it).
2017-10-22 13:33:58 -03:00
Jason Rhinelander 6a81dbbb1e Fix 2D Nx1/1xN inputs to eigen dense vector args
This fixes a bug introduced in b68959e822
when passing in a two-dimensional, but conformable, array as the value
for a compile-time Eigen vector (such as VectorXd or RowVectorXd).  The
commit switched to using numpy to copy into the eigen data, but this
broke the described case because numpy refuses to broadcast a (N,1)
into a (N).

This commit fixes it by squeezing the input array whenever the output
array is 1-dimensional, which will let the problematic case through.
(This shouldn't squeeze inappropriately as dimension compatibility is
already checked for conformability before getting to the copy code).
2017-10-12 09:45:55 -04:00
Jason Rhinelander 1b08df5872 Fix `char &` arguments being non-bindable
This changes the caster to return a reference to a (new) local `CharT`
type caster member so that binding lvalue-reference char arguments
works (currently it results in a compilation failure).

Fixes #1116
2017-10-12 09:41:54 -04:00
Jason Rhinelander 64a99b92fe Specify minimum needed cmake version in test suite
Fixes #1117
2017-09-28 08:04:34 -03:00
Ansgar Burchardt a22dd2d1df correct stride in matrix example and test
This also matches the Eigen example for the row-major case.

This also enhances one of the tests to trigger a failure (and fixes it in the PR).  (This isn't really a flaw in pybind itself, but rather fixes wrong code in the test code and docs).
2017-09-21 18:07:48 -03:00
Jason Rhinelander d2757d0440 Remove superfluous "requires_numpy"
The entire test file is already marked as requiring numpy; it isn't
needed on the individual test.
2017-09-19 23:17:21 -03:00
Jason Rhinelander c6a57c10d1 Fix dtype string leak
`PyArray_DescrConverter_` doesn't steal a reference to the argument,
and so the passed arguments shouldn't be `.release()`d.
2017-09-19 23:16:45 -03:00
Dean Moldovan c10ac6cf1f Make it possible to generate constexpr signatures in C++11 mode
The current C++14 constexpr signatures don't require relaxed constexpr,
but only `auto` return type deduction. To get around this in C++11,
the type caster's `name()` static member functions are turned into
`static constexpr auto` variables.
2017-09-16 12:02:49 +02:00
Dean Moldovan 2b4477eb65 Make TypeErrors more informative when an optional header is missing
E.g. trying to convert a `list` to a `std::vector<int>` without
including <pybind11/stl.h> will now raise an error with a note that
suggests checking the headers.

The note is only appended if `std::` is found in the function
signature. This should only be the case when a header is missing.
E.g. when stl.h is included, the signature would contain `List[int]`
instead of `std::vector<int>` while using stl_bind.h would produce
something like `MyVector`. Similarly for `std::map`/`Dict`, `complex`,
`std::function`/`Callable`, etc.

There's a possibility for false positives, but it's pretty low.
2017-09-12 08:06:46 +02:00
Gunnar Läthén c64e6b1670 Added function for reloading module (#1040) 2017-09-12 08:05:05 +02:00
Dean Moldovan 2cf87a54d8 Fix implicit conversion of accessors to types derived from py::object
Fixes #1069.
2017-09-11 10:09:32 +02:00
Dean Moldovan 7b1de1e551 Fix nullptr dereference when loading an external-only module_local type 2017-09-10 12:28:03 +02:00
Dean Moldovan 3c4933cb50 Fix STL casters for containers with proxies (regression)
To avoid an ODR violation in the test suite while testing
both `stl.h` and `std_bind.h` with `std::vector<bool>`,
the `py::bind_vector<std::vector<bool>>` test is moved to
the secondary module (which does not include `stl.h`).
2017-09-10 12:25:10 +02:00
Dean Moldovan 00b8f3655d Relax py::pickle() get/set type check
Fixes #1061.

`T` and `const T &` are compatible types.
2017-09-06 15:20:52 +02:00
Dean Moldovan 7939f4b3fe Fix application of keep_alive policy to constructors (regression) 2017-09-06 10:21:11 +02:00
Dean Moldovan 6898679270 Update enum_ and bind_vector to new-style init and pickle
Fixes #1046.
2017-08-31 01:28:07 +02:00
Bruce Merry 37de2da9dd Access C++ hash functions from Python and vice versa (#1034)
There are two separate additions:

1. `py::hash(obj)` is equivalent to the Python `hash(obj)`.
2. `.def(hash(py::self))` registers the hash function defined by
   `std::hash<T>` as the Python hash function.
2017-08-30 14:22:00 +02:00
Florian Apolloner 29b99a11a4 Specify CXX as project language for CMake >= 3.4 (#1027) 2017-08-30 14:17:54 +02:00
Dean Moldovan 1e5a7da30d Add py::pickle() adaptor for safer __getstate__/__setstate__ bindings
This is analogous to `py::init()` vs `__init__` + placement-new.
`py::pickle()` reuses most of the implementation details of `py::init()`.
2017-08-30 11:11:38 +02:00
Wenzel Jakob 8ed5b8ab55 make implicit conversions non-reentrant (fixes #1035) (#1037) 2017-08-28 16:34:06 +02:00
Dean Moldovan 39fd6a9463 Reduce binary size overhead of new-style constructors
The lookup of the `self` type and value pointer are moved out of
template code and into `dispatcher`. This brings down the binary
size of constructors back to the level of the old placement-new
approach. (It also avoids a second lookup for `init_instance`.)

With this implementation, mixing old- and new-style constructors
in the same overload set may result in some runtime overhead for
temporary allocations/deallocations, but this should be fine as
old style constructors are phased out.
2017-08-28 16:08:53 +02:00
Dean Moldovan c40ef612cc Skip boost::variant tests on unsupported compilers and versions of Boost 2017-08-25 21:11:36 +02:00