Commit Graph

136 Commits

Author SHA1 Message Date
Wenzel Jakob cd7eacc584 fix segfault in test suite due to typo (fixes #586) 2017-01-04 15:05:20 +01:00
Wenzel Jakob 0e49c02213 use a more conservative mechanism to check for pytest
On a debian jessie machine, running 'python --version --noconftest' caused
pytest to try and run the test suite with the not-yet-compiled extension
module, thus failing the test. This commit chages the pytest detection
so that it only attempts to run an import statement.
2017-01-04 08:00:17 -05:00
Wenzel Jakob 64cb699e8a disable dynamic attribute test on pypy 2016-12-26 13:54:47 +01:00
Yung-Yu Chen c40d8c617f Fix segfault when repr() with pybind11 type with metaclass (#571)
* Fixed a regression that was introduced in the PyPy patch: use ht_qualname_meta instead of ht_qualname to fix PyHeapTypeObject->ht_qualname field.

* Added a qualname/repr test that works in both Python 3.3+ and previous versions
2016-12-26 11:25:42 +01:00
Dean Moldovan 06b9397c72 Add 'check' target to run all available tests 2016-12-19 16:34:48 +01:00
Dean Moldovan 71e8a7962c Rename target from pybind11::pybind11 to pybind11::module
Makes room for an eventual pybind11::embedded target.
2016-12-19 16:34:48 +01:00
Dean Moldovan 0cbec5c96e Add new options and docs for pybind11_add_module
See the documentation for a description of the options.
2016-12-19 16:34:48 +01:00
Dean Moldovan b0f3885c95 Make sure add_subdirectory and find_package behave identically
Add a BUILD_INTERFACE and a pybind11::pybind11 alias for the interface
library to match the installed target.

Add new cmake tests for add_subdirectory and consolidates the
.cpp and .py files needed for the cmake build tests:

Before:
tests
|-- test_installed_module
|   |-- CMakeLists.txt
|   |-- main.cpp
|   \-- test.py
\-- test_installed_target
    |-- CMakeLists.txt
    |-- main.cpp
    \-- test.py

After:
tests
\-- test_cmake_build
    |-- installed_module/CMakeLists.txt
    |-- installed_target/CMakeLists.txt
    |-- subdirectory_module/CMakeLists.txt
    |-- subdirectory_target/CMakeLists.txt
    |-- main.cpp
    \-- test.py
2016-12-19 16:34:48 +01:00
Wenzel Jakob 1d1f81b278 WIP: PyPy support (#527)
This commit includes modifications that are needed to get pybind11 to work with PyPy. The full test suite compiles and runs except for a last few functions that are commented out (due to problems in PyPy that were reported on the PyPy bugtracker).

Two somewhat intrusive changes were needed to make it possible: two new tags ``py::buffer_protocol()`` and ``py::metaclass()`` must now be specified to the ``class_`` constructor if the class uses the buffer protocol and/or requires a metaclass (e.g. for static properties).

Note that this is only for the PyPy version based on Python 2.7 for now. When the PyPy 3.x has caught up in terms of cpyext compliance, a PyPy 3.x patch will follow.
2016-12-16 15:00:46 +01:00
Wenzel Jakob 2029171211 always_construct_holder feature to support intrusively reference-counted types (#561)
* always_construct_holder feature to support intrusively reference-counted types

* added testcase
2016-12-15 23:44:23 +01:00
Jason Rhinelander fa5d05e15d Change all_of_t/any_of_t to all_of/any_of, add none_of
This replaces the current `all_of_t<Pred, Ts...>` with `all_of<Ts...>`,
with previous use of `all_of_t<Pred, Ts...>` becoming
`all_of<Pred<Ts>...>` (and similarly for `any_of_t`).  It also adds a
`none_of<Ts...>`, a shortcut for `negation<any_of<Ts...>>`.

This allows `all_of` and `any_of` to be used a bit more flexible, e.g.
in cases where several predicates need to be tested for the same type
instead of the same predicate for multiple types.

This commit replaces the implementation with a more efficient version
for non-MSVC.  For MSVC, this changes the workaround to use the
built-in, recursive std::conjunction/std::disjunction instead.

This also removes the `count_t` since `any_of_t` and `all_of_t` were the
only things using it.

This commit also rearranges some of the future std imports to use actual
`std` implementations for C++14/17 features when under the appropriate
compiler mode, as we were already doing for a few things (like
index_sequence).  Most of these aren't saving much (the implementation
for enable_if_t, for example, is trivial), but I think it makes the
intention of the code instantly clear.  It also enables MSVC's native
std::index_sequence support.
2016-12-14 20:42:36 +01:00
Jason Rhinelander 6e036e78a7 Support binding noexcept function/methods in C++17
When compiling in C++17 mode the noexcept specifier is part of the
function type.  This causes a failure in pybind11 because, by omitting
a noexcept specifier when deducing function return and argument types,
we are implicitly making `noexcept(false)` part of the type.

This means that functions with `noexcept` fail to match the function
templates in cpp_function (and other places), and we get compilation
failure (we end up trying to fit it into the lambda function version,
which fails since a function pointer has no `operator()`).

We can, however, deduce the true/false `B` in noexcept(B), so we don't
need to add a whole other set of overloads, but need to deduce the extra
argument when under C++17.  That will *not* work under pre-C++17,
however.

This commit adds two macros to fix the problem: under C++17 (with the
appropriate feature macro set) they provide an extra `bool NoExceptions`
template argument and provide the `noexcept(NoExceptions)` deduced
specifier.  Under pre-C++17 they expand to nothing.

This is needed to compile pybind11 with gcc7 under -std=c++17.
2016-12-14 20:40:49 +01:00
Jason Rhinelander 79de508ef4 Fix test compilation when both optional's exist
gcc 7 has both std::experimental::optional and std::optional, but this
breaks the test compilation as we are trying to use the same `opt_int`
type alias for both.
2016-12-14 20:40:49 +01:00
Lori A. Burns eb09af5e58 test installed pybind 2016-12-13 21:44:19 +01:00
Dean Moldovan 76e993a3f4 Set maximum line length for Python style checker (#552) 2016-12-13 00:59:28 +01:00
Jason Rhinelander 3f1ff3f4d1 Adds automatic casting on assignment of non-pyobject types (#551)
This adds automatic casting when assigning to python types like dict,
list, and attributes.  Instead of:

    dict["key"] = py::cast(val);
    m.attr("foo") = py::cast(true);
    list.append(py::cast(42));

you can now simply write:

    dict["key"] = val;
    m.attr("foo") = true;
    list.append(42);

Casts needing extra parameters (e.g. for a non-default rvp) still
require the py::cast() call. set::add() is also supported.

All usage is channeled through a SFINAE implementation which either just returns or casts. 

Combined non-converting handle and autocasting template methods via a
helper method that either just returns (handle) or casts (C++ type).
2016-12-12 23:42:52 +01:00
Dean Moldovan 4e959c9af4 Add syntax sugar for resolving overloaded functions (#541) 2016-12-08 11:07:52 +01:00
Jason Rhinelander ae185b7f19 std::valarray support for stl.h (#545)
* Added ternary support with descr args

Current the `_<bool>(a, b)` ternary support only works for `char[]` `a`
and `b`; this commit allows it to work for `descr` `a` and `b` arguments
as well.

* Add support for std::valarray to stl.h

This abstracts the std::array into a `array_caster` which can then be
used with either std::array or std::valarray, the main difference being
that std::valarray is resizable.  (It also lets the array_caster be
potentially used for other std::array-like interfaces, much as the
list_caster and map_caster currently provide).

* Small stl.h cleanups

- Remove redundant `type` typedefs
- make internal list_caster methods private
2016-12-08 00:43:29 +01:00
Dean Moldovan ab90ec6ce9 Allow references to objects held by smart pointers (#533) 2016-12-07 02:36:44 +01:00
Dean Moldovan 107285b353 Accept any sequence type as std::tuple or std::pair
This is more Pythonic and compliments the std::vector and std::list
casters which also accept sequences.
2016-12-03 23:13:53 +01:00
Jason Rhinelander f200493716 Fixed stl casters to use the appropriate type_caster cast_op_type (#529)
stl casters were using a value cast to (Value) or (Key), but that isn't
always appropriate.  This changes it to use the appropriate value
converter's cast_op_type.
2016-11-25 13:06:18 +01:00
Patrick Stewart 5271576828 Use correct itemsize when constructing a numpy dtype from a buffer_info 2016-11-22 22:01:03 +01:00
patstew 47681c183d Only mark unaligned types in buffers (#505)
Previously all types are marked unaligned in buffer format strings,
now we test for alignment before adding the '=' marker.
2016-11-22 12:17:07 +01:00
Jason Rhinelander 7146d6299c Changed "Invoked with" output to use repr() instead of str() (#518)
This gives more informative output, often including the type (or at
least some hint about the type).
2016-11-22 11:28:40 +01:00
Dean Moldovan bad1740213 Add checks to maintain a consistent Python code style and prevent bugs (#515)
A flake8 configuration is included in setup.cfg and the checks are
executed automatically on Travis:

* Ensures a consistent PEP8 code style
* Does basic linting to prevent possible bugs
2016-11-20 21:21:54 +01:00
Dean Moldovan d079f41c26 Always use return_value_policy::move for rvalues (#510)
Fixes #509.

The move policy was already set for rvalues in PR #473, but this only
applied to directly cast user-defined types. The problem is that STL
containers cast values indirectly and the rvalue information is lost.
Therefore the move policy was not set correctly. This commit fixes it.

This also makes an additional adjustment to remove the `copy` policy
exception: rvalues now always use the `move` policy. This is also safe
for copy-only rvalues because the `move` policy has an internal fallback
to copying.
2016-11-20 05:31:02 +01:00
Wenzel Jakob 7c2461eefd resolve issue involving inheritance + def_static + override (fixes #511) 2016-11-20 05:26:02 +01:00
Wenzel Jakob 405f6d1dfd make arithmetic operators of enum_ optional (#508)
Following commit 90d278, the object code generated by the python
bindings of nanogui (github.com/wjakob/nanogui) went up by a whopping
12%. It turns out that that project has quite a few enums where we don't
really care about arithmetic operators.

This commit thus partially reverts the effects of #503 by introducing
an additional attribute py::arithmetic() that must be specified if the
arithmetic operators are desired.
2016-11-17 23:24:47 +01:00
Lori A. Burns 99ddc9ac1a equals needed for test_copy_move_policies to build icpc 2016.3 (#507) 2016-11-17 11:01:11 +01:00
Dean Moldovan 4de271027d Improve consistency of array and array_t with regard to other pytypes
* `array_t(const object &)` now throws on error
* `array_t::ensure()` is intended for casters —- old constructor is
  deprecated
* `array` and `array_t` get default constructors (empty array)
* `array` gets a converting constructor
* `py::isinstance<array_T<T>>()` checks the type (but not flags)

There is only one special thing which must remain: `array_t` gets
its own `type_caster` specialization which uses `ensure` instead
of a simple check.
2016-11-17 08:55:42 +01:00
Dean Moldovan e18bc02fc9 Add default and converting constructors for all concrete Python types
* Deprecate the `py::object::str()` member function since `py::str(obj)`
  is now equivalent and preferred

* Make `py::repr()` a free function

* Make sure obj.cast<T>() works as expected when T is a Python type

`obj.cast<T>()` should be the same as `T(obj)`, i.e. it should convert
the given object to a different Python type. However, `obj.cast<T>()`
usually calls `type_caster::load()` which only checks the type without
doing any actual conversion. That causes a very unexpected `cast_error`.
This commit makes it so that `obj.cast<T>()` and `T(obj)` are the same
when T is a Python type.

* Simplify pytypes converting constructor implementation

It's not necessary to maintain a full set of converting constructors
and assignment operators + const& and &&. A single converting const&
constructor will work and there is no impact on binary size. On the
other hand, the conversion functions can be significantly simplified.
2016-11-17 08:55:42 +01:00
Dean Moldovan b4498ef44d Add py::isinstance<T>(obj) for generalized Python type checking
Allows checking the Python types before creating an object instead of
after. For example:
```c++
auto l = list(ptr, true);
if (l.check())
   // ...
```
The above is replaced with:
```c++
if (isinstance<list>(ptr)) {
    auto l = reinterpret_borrow(ptr);
    // ...
}
```

This deprecates `py::object::check()`. `py::isinstance()` covers the
same use case, but it can also check for user-defined types:
```c++
class Pet { ... };
py::class_<Pet>(...);

m.def("is_pet", [](py::object obj) {
    return py::isinstance<Pet>(obj); // works as expected
});
```
2016-11-17 08:55:42 +01:00
Sylvain Corlay 5027c4f95b Switch NumPy variadic indexing to per-value arguments (#500)
* Also added unsafe version without checks
2016-11-16 17:53:37 +01:00
Pim Schellart 90d27805b9 Extended enum support (#503)
* Allow enums to be ordered
* Support binary operators
2016-11-16 17:28:11 +01:00
Jason Rhinelander 2e76daa53f Enable testing for <optional> when available (#501) 2016-11-15 22:24:26 +01:00
Ivan Smirnov 425b4970b2 Add type casters for nullopt_t, fix none refcount (#499)
* Incref returned None in std::optional type caster

* Add type casters for nullopt_t

* Add a test for nullopt_t
2016-11-15 13:00:38 +01:00
Alexander Stukowski 9a110e6da8 Provide more control over automatic generation of docstrings (#486)
Added the docstring_options class, which gives global control over the generation of docstrings and function signatures.
2016-11-15 12:38:05 +01:00
Jason Rhinelander 617fbcfc1e Fix stl_bind to support movable, non-copyable value types (#490)
This commit includes the following changes:

* Don't provide make_copy_constructor for non-copyable container

make_copy_constructor currently fails for various stl containers (e.g.
std::vector, std::unordered_map, std::deque, etc.) when the container's
value type (e.g. the "T" or the std::pair<K,T> for a map) is
non-copyable.  This adds an override that, for types that look like
containers, also requires that the value_type be copyable.

* stl_bind.h: make bind_{vector,map} work for non-copy-constructible types

Most stl_bind modifiers require copying, so if the type isn't copy
constructible, we provide a read-only interface instead.

In practice, this means that if the type is non-copyable, it will be,
for all intents and purposes, read-only from the Python side (but
currently it simply fails to compile with such a container).

It is still possible for the caller to provide an interface manually
(by defining methods on the returned class_ object), but this isn't
something stl_bind can handle because the C++ code to construct values
is going to be highly dependent on the container value_type.

* stl_bind: copy only for arithmetic value types

For non-primitive types, we may well be copying some complex type, when
returning by reference is more appropriate.  This commit returns by
internal reference for all but basic arithmetic types.

* Return by reference whenever possible

Only if we definitely can't--i.e. std::vector<bool>--because v[i]
returns something that isn't a T& do we copy; for everything else, we
return by reference.

For the map case, we can always return by reference (at least for the
default stl map/unordered_map).
2016-11-15 12:30:38 +01:00
Jason Rhinelander 0780655808 Fix test compilation failure under gcc 4.9 (#496) 2016-11-13 10:41:31 +09:00
Jason Rhinelander 920e0e349d Add cmake option to override tests (#489)
When working on some particular feature, it's nice to be able to disable
all the tests except for the one I'm working on; this is currently
possible by editing tests/CMakeLists.txt, and commenting out the tests
you don't want.

This commit goes a step further by letting you give a list of tests you
do want when invoking cmake, e.g.:

    cmake -DPYBIND11_TEST_OVERRIDE="test_issues.cpp;test_pickling.cpp" ..

changes the build to build just those two tests (and changes the `pytest`
target to invoke just the two associated tests).

This persists in the build directory until you disable it again by
running cmake with `-DPYBIND11_TEST_OVERRIDE=`.  It also adds a message
after the pytest output to remind you that it is in effect:

    Note: not all tests run: -DPYBIND11_TEST_OVERRIDE is in effect
2016-11-13 09:10:53 +09:00
Wenzel Jakob fe40dfe67d address number caster regression (fixes #484) 2016-11-07 15:59:01 +01:00
Jason Rhinelander c07ec31edf Don't construct unique_ptr around unowned pointers (#478)
If we need to initialize a holder around an unowned instance, and the
holder type is non-copyable (i.e. a unique_ptr), we currently construct
the holder type around the value pointer, but then never actually
destruct the holder: the holder destructor is called only for the
instance that actually has `inst->owned = true` set.

This seems no pointer, however, in creating such a holder around an
unowned instance: we never actually intend to use anything that the
unique_ptr gives us: and, in fact, do not want the unique_ptr (because
if it ever actually got destroyed, it would cause destruction of the
wrapped pointer, despite the fact that that wrapped pointer isn't
owned).

This commit changes the logic to only create a unique_ptr holder if we
actually own the instance, and to destruct via the constructed holder
whenever we have a constructed holder--which will now only be the case
for owned-unique-holder or shared-holder types.

Other changes include:

* Added test for non-movable holder constructor/destructor counts

The three alive assertions now pass, before #478 they fail with counts
of 2/2/1 respectively, because of the unique_ptr that we don't want and
don't destroy (because we don't *want* its destructor to run).

* Return cstats reference; fix ConstructStats doc

Small cleanup to the #478 test code, and fix to the ConstructStats
documentation (the static method definition should use `reference` not
`reference_internal`).

* Rename inst->constructed to inst->holder_constructed

This makes it clearer exactly what it's referring to.
2016-11-06 19:12:48 +01:00
Jason Rhinelander dc0b4bd2c9 Add debugging info about .so size to build output (#477)
* Add debugging info about so size to build output

This adds a small python script to tools that captures before-and-after
.so sizes between builds and outputs this in the build output via a
string such as:

------ pybind11_tests.cpython-35m-x86_64-linux-gnu.so file size: 924696 (decrease of 73680 bytes = 7.38%)

------ pybind11_tests.cpython-35m-x86_64-linux-gnu.so file size: 998376 (increase of 73680 bytes = 7.97%)

------ pybind11_tests.cpython-35m-x86_64-linux-gnu.so file size: 998376 (no change)

Or, if there was no .so during the build, just the .so size by itself:

------ pybind11_tests.cpython-35m-x86_64-linux-gnu.so file size: 998376

This allows you to, for example, build, checkout a different branch,
rebuild, and easily see exactly the change in the pybind11_tests.so
size.

It also allows looking at the travis and appveyor build logs to get an
idea of .so/.dll sizes across different build systems.

* Minor libsize.py script changes

- Use RAII open
- Remove unused libsize=-1
- Report change as [+-]xyz bytes = [+-]a.bc%
2016-11-04 14:47:41 +01:00
Ivan Smirnov 44a69f78cf std::experimental::optional (#475)
* Add type caster for std::experimental::optional

* Add tests for std::experimental::optional

* Support both <optional> / <experimental/optional>

* Mention std{::experimental,}::optional in the docs
2016-11-03 13:42:46 +01:00
Wenzel Jakob bd560acf40 smart pointer refcount fix by @dean0x7d with slight modifications (fixes #471) 2016-11-03 11:53:35 +01:00
Ivan Smirnov c546655dc2 Use pytest fixtures in numpy dtypes test module 2016-11-03 09:35:05 +00:00
Ivan Smirnov 2184f6d4d6 NumPy dtypes are now shared across extensions 2016-11-03 09:35:05 +00:00
Wenzel Jakob a743ead455 Merge pull request #474 from aldanor/feature/numpy-dtype-ex
Overriding field names when binding structured dtypes
2016-11-03 09:44:30 +01:00
Ivan Smirnov abd3429ce9 Add a test for numpy dtypes with custom names 2016-11-01 13:29:32 +00:00
Dean Moldovan 03f627ebb1 Make reference(_internal) the default return value policy for properties (#473)
* Make reference(_internal) the default return value policy for properties

Before this, all `def_property*` functions used `automatic` as their
default return value policy. This commit makes it so that:

 * Non-static properties use `reference_interal` by default, thus
   matching `def_readonly` and `def_readwrite`.

 * Static properties use `reference` by default, thus matching
   `def_readonly_static` and `def_readwrite_static`.

In case `cpp_function` is passed to any `def_property*`, its policy will
be used instead of any defaults. User-defined arguments in `extras`
still have top priority and will override both the default policies and
the ones from `cpp_function`.

Resolves #436.

* Almost always use return_value_policy::move for rvalues

For functions which return rvalues or rvalue references, the only viable
return value policies are `copy` and `move`. `reference(_internal)` and
`take_ownership` would take the address of a temporary which is always
an error.

This commit prevents possible user errors by overriding the bad rvalue
policies with `move`. Besides `move`, only `copy` is allowed, and only
if it's explicitly selected by the user.

This is also a necessary safety feature to support the new default
return value policies for properties: `reference(_internal)`.
2016-11-01 11:44:57 +01:00