Commit Graph

206 Commits

Author SHA1 Message Date
Wenzel Jakob e6fd2cd5ab enum_: fix implicit conversion on Python 2.7
Enumerations on Python 2.7 were not always implicitly converted to
integers (depending on the target size). This patch adds a __long__
conversion function (only enabled on 2.7) which fixes this issue.

The attached test case fails without this patch.
2017-04-29 16:35:28 +02:00
Jason Rhinelander 51d18aa252 Fix ambiguous initialize_list arguments
This removes the convert-from-arithemtic-scalar constructor of
any_container as it can result in ambiguous calls, as in:

    py::array_t<float>({ 1, 2 })

which could be intepreted as either of:

    py::array_t<float>(py::array_t<float>(1, 2))
    py::array_t<float>(py::detail::any_container({ 1, 2 }))

Removing the convert-from-arithmetic constructor reduces the number of
implicit conversions, avoiding the ambiguity for array and array_t.
This also re-adds the array/array_t constructors taking a scalar
argument for backwards compatibility.
2017-04-28 14:12:06 -04:00
Jason Rhinelander 0a90b2db71 Don't let PyInstanceMethod hide itself
Python 3's `PyInstanceMethod_Type` hides itself via its `tp_descr_get`,
which prevents aliasing methods via `cls.attr("m2") = cls.attr("m1")`:
instead the `tp_descr_get` returns a plain function, when called on a
class, or a `PyMethod`, when called on an instance.  Override that
behaviour for pybind11 types with a special bypass for
`PyInstanceMethod_Types`.
2017-04-28 11:18:58 -04:00
Jason Rhinelander a7f704b39b Fix Python 3 `bytes` conversion to std::string/char*
The Unicode support added in 2.1 (PR #624) inadvertently broke accepting
`bytes` as std::string/char* arguments.  This restores it with a
separate path that does a plain conversion (i.e. completely bypassing
all the encoding/decoding code), but only for single-byte string types.
2017-04-28 11:14:14 -04:00
Jason Rhinelander 1f8a100d38 Track base class pointers of instances
This commits adds base class pointers of offset base classes (i.e. due
to multiple inheritance) to `registered_instances` so that if such a
pointer is returned we properly recognize it as an existing instance.

Without this, returning a base class pointer will cast to the existing
instance if the pointer happens to coincide with the instance pointer,
but constructs a new instance (quite possibly with a segfault, if
ownership is applied) for unequal base class pointers due to multiple
inheritance.
2017-04-27 09:12:41 -04:00
Jason Rhinelander 14e70650fe Fix downcasting of base class pointers
When we are returned a base class pointer (either directly or via
shared_from_this()) we detect its runtime type (using `typeid`), then
end up essentially reinterpret_casting the pointer to the derived type.
This is invalid when the base class pointer was a non-first base, and we
end up with an invalid pointer.  We could dynamic_cast to the
most-derived type, but if *that* type isn't pybind11-registered, the
resulting pointer given to the base `cast` implementation isn't necessarily valid
to be reinterpret_cast'ed back to the backup type.

This commit removes the "backup" type argument from the many-argument
`cast(...)` and instead does the derived-or-pointer type decision and
type lookup in type_caster_base, where the dynamic_cast has to be to
correctly get the derived pointer, but also has to do the type lookup to
ensure that we don't pass the wrong (derived) pointer when the backup
type (i.e. the type caster intrinsic type) pointer is needed.

Since the lookup is needed before calling the base cast(), this also
changes the input type to a detail::type_info rather than doing a
(second) lookup in cast().
2017-04-27 09:12:41 -04:00
Jason Rhinelander d355f2fcca Don't allow mixed static/non-static overloads
We currently fail at runtime when trying to call a method that is
overloaded with both static and non-static methods.  This is something
python won't allow: the object is either a function or an instance, and
can't be both.
2017-04-18 17:17:47 -04:00
Jason Rhinelander 90bac96321 Keep skipping buffer tests on pypy
Adding numpy to the pypy test exposed a segfault caused by the buffer
tests in test_stl_binders.py: the first such test was explicitly skipped
on pypy, but the second (test_vector_buffer_numpy) which also seems to
cause an occasional segfault was just marked as requiring numpy.

Explicitly skip it on pypy as well (until a workaround, fix, or pypy fix
are found).
2017-04-18 14:21:31 -04:00
Jason Rhinelander 2d14c1c5db Fixed bad_arg_def imports
Don't try to define these in the issues submodule, because that fails
if testing without issues compiled in (e.g. using
cmake -DPYBIND11_TEST_OVERRIDE=test_methods_and_attributes.cpp).
2017-04-15 11:12:41 -04:00
Jason Rhinelander 5f38386293 Accept abitrary containers and iterators for shape/strides
This adds support for constructing `buffer_info` and `array`s using
arbitrary containers or iterator pairs instead of requiring a vector.

This is primarily needed by PR #782 (which makes strides signed to
properly support negative strides, and will likely also make shape and
itemsize to avoid mixed integer issues), but also needs to preserve
backwards compatibility with 2.1 and earlier which accepts the strides
parameter as a vector of size_t's.

Rather than adding nearly duplicate constructors for each stride-taking
constructor, it seems nicer to simply allow any type of container (or
iterator pairs).  This works by replacing the existing vector arguments
with a new `detail::any_container` class that handles implicit
conversion of arbitrary containers into a vector of the desired type.
It can also be explicitly instantiated with a pair of iterators (e.g.
by passing {begin, end} instead of the container).
2017-04-13 09:57:02 -04:00
Jason Rhinelander 5749b50239 array: set exception message on failure
When attempting to get a raw array pointer we return nullptr if given a
nullptr, which triggers an error_already_set(), but we haven't set an
exception message, which results in "Unknown internal error".

Callers that want explicit allowing of a nullptr here already handle it
(by clearing the exception after the call).
2017-04-13 09:53:56 -04:00
Jason Rhinelander e9e17746c8 Fix Eigen argument doc strings
Many of the Eigen type casters' name() methods weren't wrapping the type
description in a `type_descr` object, which thus wasn't adding the
"{...}" annotation used to identify an argument which broke the help
output by skipping eigen arguments.

The test code I had added even had some (unnoticed) broken output (with
the "arg0: " showing up in the return value).

This commit also adds test code to ensure that named eigen arguments
actually work properly, despite the invalid help output.  (The added
tests pass without the rest of this commit).
2017-04-08 23:25:13 -04:00
Dean Moldovan e0e2ea3378 Fix overriding static properties in derived classes
Fixes #775.

Assignments of the form `Type.static_prop = value` should be translated to
`Type.static_prop.__set__(value)` except when `isinstance(value, static_prop)`.
2017-04-07 22:41:46 +02:00
Dean Moldovan 555dc4f07a Fix test_cmake_build failure with bare python exe name (fix #783)
Besides appearing in the CMake GUI, the `:FILENAME` specifier changes
behavior as well:

cmake -DPYTHON_EXECUTABLE=python ..  # FAIL, can't find python
cmake -DPYTHON_EXECUTABLE=/path/to/python ..  # OK
cmake -DPYTHON_EXECUTABLE:FILENAME=python ..  # OK
cmake -DPYTHON_EXECUTABLE:FILENAME=/path/to/python ..  # OK
2017-04-06 22:41:32 +02:00
Jason Rhinelander 6906b270d6 Improve make_tuple error message under debugging
When make_tuple fails (for example, when print() is called with a
non-convertible argument, as in #778) the error message a less helpful
than it could be:

    make_tuple(): unable to convert arguments of types 'std::tuple<type1, type2>' to Python object

There is no actual std::tuple involved (only a parameter pack and a
Python tuple), but it also doesn't immediately reveal which type caused
the problem.

This commit changes the debugging mode output to show just the
problematic type:

    make_tuple(): unable to convert argument of type 'type2' to Python object
2017-04-05 11:43:05 -04:00
Dean Moldovan 1ac19036d6 Add a scope guard call policy
```c++
m.def("foo", foo, py::call_guard<T>());
```

is equivalent to:

```c++
m.def("foo", [](args...) {
    T scope_guard;
    return foo(args...); // forwarded arguments
});
```
2017-04-03 00:52:47 +02:00
Roman Miroshnychenko 83a8a977a7 Add a method to check Python exception types (#772)
This commit adds `error_already_set::matches()` convenience method to
check if the exception trapped by `error_already_set` matches a given
Python exception type. This will address #700 by providing a less
verbose way to check exceptions.
2017-04-02 22:38:50 +02:00
Dean Moldovan 194d8b99b3 Support raw string literals as input for py::eval (#766)
* Support raw string literals as input for py::eval
* Dedent only when needed
2017-03-29 00:27:56 +02:00
Wenzel Jakob b16421edb1 Nicer API to pass py::capsule destructor (#752)
* nicer py::capsule destructor mechanism
* added destructor-only version of capsule & tests
* added documentation for module destructors (fixes #733)
2017-03-22 22:04:00 +01:00
Jason Rhinelander 773339f131 array-unchecked: add runtime dimension support and array-compatible methods
The extends the previous unchecked support with the ability to
determine the dimensions at runtime.  This incurs a small performance
hit when used (versus the compile-time fixed alternative), but is still considerably
faster than the full checks on every call that happen with
`.at()`/`.mutable_at()`.
2017-03-22 16:15:56 -03:00
Jason Rhinelander 423a49b8be array: add unchecked access via proxy object
This adds bounds-unchecked access to arrays through a `a.unchecked<Type,
Dimensions>()` method.  (For `array_t<T>`, the `Type` template parameter
is omitted).  The mutable version (which requires the array have the
`writeable` flag) is available as `a.mutable_unchecked<...>()`.

Specifying the Dimensions as a template parameter allows storage of an
std::array; having the strides and sizes stored that way (as opposed to
storing a copy of the array's strides/shape pointers) allows the
compiler to make significant optimizations of the shape() method that it
can't make with a pointer; testing with nested loops of the form:

    for (size_t i0 = 0; i0 < r.shape(0); i0++)
        for (size_t i1 = 0; i1 < r.shape(1); i1++)
            ...
                r(i0, i1, ...) += 1;

over a 10 million element array gives around a 25% speedup (versus using
a pointer) for the 1D case, 33% for 2D, and runs more than twice as fast
with a 5D array.
2017-03-22 16:13:59 -03:00
Dean Moldovan 0d765f4a7c Support class-specific operator new and delete
Fixes #754.
2017-03-22 19:28:04 +01:00
Jason Rhinelander b0292c1df3 vectorize: trivial handling for F-order arrays
This extends the trivial handling to support trivial handling for
Fortran-order arrays (i.e. column major): if inputs aren't all
C-contiguous, but *are* all F-contiguous, the resulting array will be
F-contiguous and we can do trivial processing.

For anything else (e.g. C-contiguous, or inputs requiring non-trivial
processing), the result is in (numpy-default) C-contiguous layout.
2017-03-21 18:53:56 -03:00
Jason Rhinelander ae5a8f7eb3 Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)

This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.

Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-21 18:53:56 -03:00
Dean Moldovan cd3d1fc7df Throw an exception when attempting to load an incompatible holder
Instead of a segfault. Fixes #751.

This covers the case of loading a custom holder from a default-holder
instance. Attempting to load one custom holder from a different custom
holder (i.e. not `std::unique_ptr`) yields undefined behavior, just as
#588 established for inheritance.
2017-03-21 10:26:22 +01:00
Jason Rhinelander b961626c0c Fail to compile with MI via class_ ctor parameters
We can't support this for classes from imported modules (which is the
primary purpose of a ctor argument base class) because we *have* to
have both parent and derived to properly extract a multiple-inheritance
base class pointer from a derived class pointer.

We could support this for actual `class_<Base, ...> instances, but since
in that case the `Base` is already present in the code, it seems more
consistent to simply always require MI to go via template options.
2017-03-17 15:35:34 -03:00
Jason Rhinelander efa8726ff7 Eigen: don't require conformability on length-1 dimensions
Fixes #738

The current check for conformability fails when given a 2D, 1xN or Nx1
input to a row-major or column-major, respectively, Eigen::Ref, leading
to a copy-required state in the type_caster, but this later failed
because the copy was also non-conformable because it had the same shape
and strides (because a 1xN or Nx1 is both F and C contiguous).

In such cases we can safely ignore the stride on the "1" dimension since
it'll never be used: only the "N" dimension stride needs to match the
Eigen::Ref stride, which both fixes the non-conformable copy problem,
but also avoids a copy entirely as long as the "N" dimension has a
compatible stride.
2017-03-17 15:32:18 -03:00
Dean Moldovan 819cb5533e Fix nullptr to None conversion for builtin type casters
Fixes #731.

Generally, this applies to any caster made with PYBIND11_TYPE_CASTER().
2017-03-16 13:57:35 +01:00
Dean Moldovan 1769ea427f Add __module__ attribute to all pybind11 builtin types (#729)
Fixes #728.
2017-03-15 15:38:14 +01:00
Patrick Stewart 0b6d08a008 Add function for comparing buffer_info formats to types
Allows equivalent integral types and numpy dtypes
2017-03-14 02:50:04 +01:00
Patrick Stewart 5467979588 Add the buffer interface for wrapped STL vectors
Allows use of vectors as python buffers, so for example they can be adopted without a copy by numpy.asarray
Allows faster conversion of buffers to vectors by copying instead of individually casting the elements
2017-03-14 02:50:04 +01:00
Dean Moldovan 16afbcef46 Improve py::array_t scalar type information (#724)
* Add value_type member alias to py::array_t (resolve #632)

* Use numpy scalar name in py::array_t function signatures (e.g. float32/64 instead of just float)
2017-03-13 19:17:18 +01:00
Jason Rhinelander e5456c2226 Fix for floating point durations
The duration calculation was using %, but that's only supported on
duration objects when the arithmetic type supports %, and hence fails
for floats.  Fixed by subtracting off the calculated values instead.
2017-03-11 23:04:16 -04:00
Dean Moldovan d47febcb17 Minor pytest maintenance (#702)
* Add `pytest.ini` config file and set default options there instead of
  in `CMakeLists.txt` (command line arguments).

* Change all output capture from `capfd` (filedescriptors) to `capsys`
  (Python's `sys.stdout` and `sys.stderr`). This avoids capturing
  low-level C errors, e.g. from the debug build of Python.

* Set pytest minimum version to 3.0 to make it easier to use new
  features. Removed conditional use of `excinfo.match()`.

* Clean up some leftover function-level `@pytest.requires_numpy`.
2017-03-10 15:42:42 +01:00
Jason Rhinelander 10d1304806 Fix extra docstring newlines under `options.disable_function_signatures()`
When using pybind::options to disable function signatures, user-defined
docstrings only get appended if they exist, but newlines were getting
appended unconditionally, so the docstring could end up with blank lines
(depending on which overloads, in particular, provided docstrings).

This commit suppresses the empty lines by only adding newlines for
overloads when needed.
2017-03-08 12:32:42 -05:00
Jason Rhinelander c44fe6fda5 array_t overload resolution support
This makes array_t respect overload resolution and noconvert by failing
to load when `convert = false` if the src isn't already an array of the
correct type.
2017-03-06 14:56:22 -05:00
Matthieu Bec af936e1987 Expose enum_ entries as "__members__" read-only property. Getters get a copy. 2017-03-03 08:45:50 -08:00
Dean Moldovan 5143989623 Fix compilation of Eigen casters with complex scalars 2017-02-28 19:25:09 +01:00
Dean Moldovan 620a808ad0 Test with debug build of Python when DEBUG=1 on Travis 2017-02-28 00:27:26 +01:00
Dean Moldovan 5637af7b67 Add lightweight iterators for tuple, list and sequence
Slightly reduces binary size (range for loops over tuple/list benefit
a lot). The iterators are compatible with std algorithms.
2017-02-26 23:57:03 +01:00
Dean Moldovan 1fac1b9f5f Make py::iterator compatible with std algorithms
The added type aliases are required by `std::iterator_traits`.
Python iterators satisfy the `InputIterator` concept in C++.
2017-02-26 23:57:03 +01:00
Dean Moldovan f7685826e2 Handle all py::iterator errors
Before this, `py::iterator` didn't do any error handling, so code like:
```c++
for (auto item : py::int_(1)) {
    // ...
}
```
would just silently skip the loop. The above now throws `TypeError` as
expected. This is a breaking behavior change, but any code which relied
on the silent skip was probably broken anyway.

Also, errors returned by `PyIter_Next()` are now properly handled.
2017-02-26 23:57:03 +01:00
Wenzel Jakob cecb577a19 fix -Wunused-lambda-capture warning 2017-02-26 23:15:39 +01:00
Jason Rhinelander df244884c0 Skip .match on older pytest (pre-3.0)
Fixes test failure on Fedora 25.
2017-02-26 22:59:13 +01:00
Jason Rhinelander 0861be05da Fix numpy tests for big endian architectures
Fixes some numpy tests failures on ppc64 in big-endian mode due to
little-endian assumptions.

Fixes #694.
2017-02-26 22:59:13 +01:00
Jason Rhinelander 2a75784420 Move requires_numpy, etc. decorators to globals
test_eigen.py and test_numpy_*.py have the same
@pytest.requires_eigen_and_numpy or @pytest.requires_numpy on every
single test; this changes them to use pytest's global `pytestmark = ...`
instead to disable the entire module when numpy and/or eigen aren't
available.
2017-02-24 23:19:50 +01:00
Jason Rhinelander 17d0283eca Eigen<->numpy referencing support
This commit largely rewrites the Eigen dense matrix support to avoid
copying in many cases: Eigen arguments can now reference numpy data, and
numpy objects can now reference Eigen data (given compatible types).

Eigen::Ref<...> arguments now also make use of the new `convert`
argument use (added in PR #634) to avoid conversion, allowing
`py::arg().noconvert()` to be used when binding a function to prohibit
copying when invoking the function.  Respecting `convert` also means
Eigen overloads that avoid copying will be preferred during overload
resolution to ones that require copying.

This commit also rewrites the Eigen documentation and test suite to
explain and test the new capabilities.
2017-02-24 23:19:50 +01:00
Jason Rhinelander fd7517037b Change array's writeable exception to a ValueError
Numpy raises ValueError when attempting to modify an array, while
py::array is raising a RuntimeError.  This changes the exception to a
std::domain_error, which gets mapped to the expected ValueError in
python.
2017-02-24 23:19:50 +01:00
Jason Rhinelander f86dddf7ba array: fix base handling
numpy arrays aren't currently properly setting base: by setting `->base`
directly, the base doesn't follow what numpy expects and documents (that
is, following chained array bases to the root array).

This fixes the behaviour by using numpy's PyArray_SetBaseObject to set
the base instead, and then updates the tests to reflect the fixed
behaviour.
2017-02-24 23:19:50 +01:00
Jason Rhinelander d9d224f288 Eigen: fix partially-fixed matrix conversion
Currently when we do a conversion between a numpy array and an Eigen
Vector, we allow the conversion only if the Eigen type is a
compile-time vector (i.e. at least one dimension is fixed at 1 at
compile time), or if the type is dynamic on *both* dimensions.

This means we can run into cases where MatrixXd allow things that
conforming, compile-time sizes does not: for example,
`Matrix<double,4,Dynamic>` is currently not allowed, even when assigning
from a 4-element vector, but it *is* allowed for a
`Matrix<double,Dynamic,Dynamic>`.

This commit also reverts the current behaviour of using the matrix's
storage order to determine the structure when the Matrix is fully
dynamic (i.e. in both dimensions).  Currently we assign to an eigen row
if the storage order is row-major, and column otherwise: this seems
wrong (the storage order has nothing to do with the shape!).  While
numpy doesn't distinguish between a row/column vector, Eigen does, but
it makes more sense to consistently choose one than to produce
something with a different shape based on the intended storage layout.
2017-02-24 23:19:50 +01:00