Commit Graph

320 Commits

Author SHA1 Message Date
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
Wenzel Jakob
c14c2762f6 Address reference leak issue (fixes #1029)
Creating an instance of of a pybind11-bound type caused a reference leak in the
associated Python type object, which could prevent these from being collected
upon interpreter shutdown. This commit fixes that issue for all types that are
defined in a scope (e.g. a module). Unscoped anonymous types (e.g. custom
iterator types) always retain a positive reference count to prevent their
collection.
2017-08-25 16:02:18 +02:00
Henry Schreiner
8b40505575 Utility for redirecting C++ streams to Python (#1009) 2017-08-25 02:12:43 +02:00
Jason Rhinelander
e9bb843edc Fix clang5 warnings 2017-08-23 12:05:18 -04:00
Dean Moldovan
b33475d054 Speed up AppVeyor build (#1021)
The `latest` build remains as is, but all others are modified to:

* Use regular Python instead of conda. `pip install` is much faster
  than conda, but scipy isn't available. Numpy is still tested.

* Compile in debug mode instead of release.

* Skip CMake build tests. For some reason, CMake configuration is very
  slow on AppVeyor and these tests are almost entirely CMake.

The changes reduce build time to about 1/3 of the original. The `latest` 
config still covers scipy, release mode and the CMake build tests, so 
the others don't need to.
2017-08-23 17:18:57 +02:00
Wenzel Jakob
4336a7da4a support for brace initialization 2017-08-22 16:22:56 +02:00
Dean Moldovan
234f7c39a0 Test and document binding protected member functions 2017-08-22 12:42:27 +02:00
Jason Rhinelander
5e14aa6aa7 Allow module-local classes to be loaded externally
The main point of `py::module_local` is to make the C++ -> Python cast
unique so that returning/casting a C++ instance is well-defined.
Unfortunately it also makes loading unique, but this isn't particularly
desirable: when an instance contains `Type` instance there's no reason
it shouldn't be possible to pass that instance to a bound function
taking a `Type` parameter, even if that function is in another module.

This commit solves the issue by allowing foreign module (and global)
type loaders have a chance to load the value if the local module loader
fails.  The implementation here does this by storing a module-local
loading function in a capsule in the python type, which we can then call
if the local (and possibly global, if the local type is masking a global
type) version doesn't work.
2017-08-19 15:30:39 -04:00
Jason Rhinelander
c4e180081d Reimplement py::init<...> to use common factory code
This reimplements the py::init<...> implementations using the various
functions added to support `py::init(...)`, and moves the implementing
structs into `detail/init.h` from `pybind11.h`.  It doesn't simply use a
factory directly, as this is a very common case and implementation
without an extra lambda call is a small but useful optimization.

This, combined with the previous lazy initialization, also avoids
needing placement new for `py::init<...>()` construction: such
construction now occurs via an ordinary `new Type(...)`.

A consequence of this is that it also fixes a potential bug when using
multiple inheritance from Python: it was very easy to write classes
that double-initialize an existing instance which had the potential to
leak for non-pod classes.  With the new implementation, an attempt to
call `__init__` on an already-initialized object is now ignored.  (This
was already done in the previous commit for factory constructors).

This change exposed a few warnings (fixed here) from deleting a pointer
to a base class with virtual functions but without a virtual destructor.
These look like legitimate warnings that we shouldn't suppress; this
adds virtual destructors to the appropriate classes.
2017-08-17 09:33:27 -04:00
Jason Rhinelander
464d98962d Allow binding factory functions as constructors
This allows you to use:

    cls.def(py::init(&factory_function));

where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type).  Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.

Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
  `py::init<...>()`, but keeps the naming consistent: the existing
  templated, no-argument one wraps constructors, the no-template,
  function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
  is required (i.e. python-side inheritance and a declared alias), a
  dynamic_cast to the alias is attempted (for the pointer version); if
  it fails, or if returned by value, an Alias(Class &&) constructor
  is invoked.  If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
  the wrapped pointer to the alias to see if it is already an alias
  instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
  two factories: the first is called when an alias is not needed, the
  second when it is.
- Reimplement factory instance clearing.  The previous implementation
  failed under python-side multiple inheritance: *each* inherited
  type's factory init would clear the instance instead of only setting
  its own type value.  The new implementation here clears just the
  relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
  nullptr and the `holder_constructed` flag to false so that it can be
  used to clear preallocated value without needing to rebuild the
  instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
  completely avoid the extra overhead of needing an extra
  allocation/deallocation.
- Updated documentation to make factory constructors the default
  advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
  throw away the first instance, replacing it with the second; or we can
  ignore the second call.  The latter is slightly easier, so do that.
2017-08-17 09:33:27 -04:00
Jason Rhinelander
42e5ddc541 Add a polymorphic static assert when using an alias
An alias can be used for two main purposes: to override virtual methods,
and to add some extra data to a class needed for the pybind-wrapper.
Both of these absolutely require that the wrapped class be polymorphic
so that virtual dispatch and destruction, respectively, works.
2017-08-17 09:33:27 -04:00
Dean Moldovan
8d3cedbe2b Add test for mixing STL casters and local binders across modules
One module uses a generic vector caster from `<pybind11/stl.h>` while
the other exports `std::vector<int>` with a local `py:bind_vector`.
2017-08-14 01:11:52 +02:00
Dean Moldovan
7918bcc95b Add support for boost::variant in C++11 mode
In C++11 mode, `boost::apply_visitor` requires an explicit `result_type`.
This also adds optional tests for `boost::variant` in C++11/14, if boost
is available. In C++17 mode, `std::variant` is tested instead.
2017-08-12 21:27:44 +02:00
Dean Moldovan
3dde6ddc53 Add test for custom CMake export group 2017-08-07 23:08:20 +02:00
Jason Rhinelander
391c75447d Update all remaining tests to new test styles
This udpates all the remaining tests to the new test suite code and
comment styles started in #898.  For the most part, the test coverage
here is unchanged, with a few minor exceptions as noted below.

- test_constants_and_functions: this adds more overload tests with
  overloads with different number of arguments for more comprehensive
  overload_cast testing.  The test style conversion broke the overload
  tests under MSVC 2015, prompting the additional tests while looking
  for a workaround.

- test_eigen: this dropped the unused functions `get_cm_corners` and
  `get_cm_corners_const`--these same tests were duplicates of the same
  things provided (and used) via ReturnTester methods.

- test_opaque_types: this test had a hidden dependence on ExampleMandA
  which is now fixed by using the global UserType which suffices for the
  relevant test.

- test_methods_and_attributes: this required some additions to UserType
  to make it usable as a replacement for the test's previous SimpleType:
  UserType gained a value mutator, and the `value` property is not
  mutable (it was previously readonly).  Some overload tests were also
  added to better test overload_cast (as described above).

- test_numpy_array: removed the untemplated mutate_data/mutate_data_t:
  the templated versions with an empty parameter pack expand to the same
  thing.

- test_stl: this was already mostly in the new style; this just tweaks
  things a bit, localizing a class, and adding some missing
  `// test_whatever` comments.

- test_virtual_functions: like `test_stl`, this was mostly in the new
  test style already, but needed some `// test_whatever` comments.
  This commit also moves the inherited virtual example code to the end
  of the file, after the main set of tests (since it is less important
  than the other tests, and rather length); it also got renamed to
  `test_inherited_virtuals` (from `test_inheriting_repeat`) because it
  tests both inherited virtual approaches, not just the repeat approach.
2017-08-05 18:46:22 -04:00
Jason Rhinelander
9866a0f994 test_class: use gc_collect instead of detail_reg_inst side-effect 2017-08-05 18:46:22 -04:00
Jason Rhinelander
b468a3cefc Ignore undefined name long errors on Python 3 2017-08-05 18:46:22 -04:00
Jason Rhinelander
4b159230d9 Made module_local types take precedence over global types
Attempting to mix py::module_local and non-module_local classes results
in some unexpected/undesirable behaviour:

- if a class is registered non-local by some other module, a later
  attempt to register it locally fails.  It doesn't need to: it is
  perfectly acceptable for the local registration to simply override
  the external global registration.
- going the other way (i.e. module `A` registers a type `T` locally,
  then `B` registers the same type `T` globally) causes a more serious
  issue: `A.T`'s constructors no longer work because the `self` argument
  gets converted to a `B.T`, which then fails to resolve.

Changing the cast precedence to prefer local over global fixes this and
makes it work more consistently, regardless of module load order.
2017-08-05 11:23:34 -04:00
Jason Rhinelander
7437c69500 Add py::module_local() attribute for module-local type bindings
This commit adds a `py::module_local` attribute that lets you confine a
registered type to the module (more technically, the shared object) in
which it is defined, by registering it with:

    py::class_<C>(m, "C", py::module_local())

This will allow the same C++ class `C` to be registered in different
modules with independent sets of class definitions.  On the Python side,
two such types will be completely distinct; on the C++ side, the C++
type resolves to a different Python type in each module.

This applies `py::module_local` automatically to `stl_bind.h` bindings
when the container value type looks like something global: i.e. when it
is a converting type (for example, when binding a `std::vector<int>`),
or when it is a registered type itself bound with `py::module_local`.
This should help resolve potential future conflicts (e.g. if two
completely unrelated modules both try to bind a `std::vector<int>`.
Users can override the automatic selection by adding a
`py::module_local()` or `py::module_local(false)`.

Note that this does mildly break backwards compatibility: bound stl
containers of basic types like `std::vector<int>` cannot be bound in one
module and returned in a different module.  (This can be re-enabled with
`py::module_local(false)` as described above, but with the potential for
eventual load conflicts).
2017-08-04 10:47:34 -04:00
Jason Rhinelander
d598172993 Fix builtin exception handlers to work across modules
The builtin exception handler currently doesn't work across modules
under clang/libc++ for builtin pybind exceptions like
`pybind11::error_already_set` or `pybind11::stop_iteration`: under
RTLD_LOCAL module loading clang considers each module's exception
classes distinct types.  This then means that the base exception
translator fails to catch the exceptions and the fall through to the
generic `std::exception` handler, which completely breaks things like
`stop_iteration`: only the `stop_iteration` of the first module loaded
actually works properly; later modules raise a RuntimeError with no
message when trying to invoke their iterators.

For example, two modules defined like this exhibit the behaviour under
clang++/libc++:

z1.cpp:
    #include <pybind11/pybind11.h>
    #include <pybind11/stl_bind.h>
    namespace py = pybind11;
    PYBIND11_MODULE(z1, m) {
        py::bind_vector<std::vector<long>>(m, "IntVector");
    }

z2.cpp:
    #include <pybind11/pybind11.h>
    #include <pybind11/stl_bind.h>
    namespace py = pybind11;
    PYBIND11_MODULE(z2, m) {
        py::bind_vector<std::vector<double>>(m, "FloatVector");
    }

Python:
    import z1, z2
    for i in z2.FloatVector():
        pass

results in:
    Traceback (most recent call last):
      File "zs.py", line 2, in <module>
        for i in z2.FloatVector():
    RuntimeError

This commit fixes the issue by adding a new exception translator each
time the internals pointer is initialized from python builtins: this
generally means the internals data was initialized by some other
module.  (The extra translator(s) are skipped under libstdc++).
2017-08-04 10:47:34 -04:00
Jason Rhinelander
0bd5979c77 Add cross-module test plugin
This adds the infrastructure for a separate test plugin for cross-module
tests.  (This commit contains no tests that actually use it, but the
following commits do; this is separated simply to provide a cleaner
commit history).
2017-08-04 10:47:34 -04:00
Jason Rhinelander
373da82486 Make PYBIND11_OBJECT_CVT only convert if the type check fails
Currently types that are capable of conversion always call their convert
function when invoked with a `py::object` which is actually the correct
type.  This means that code such as `py::cast<py::list>(obj)` and
`py::list l(obj.attr("list"))` make copies, which was an oversight
rather than an intentional feature.

While at first glance there might be something behind having
`py::list(obj)` make a copy (as it would in Python), this would be
inconsistent when you dig a little deeper because `py::list(l)`
*doesn't* make a copy for an existing `py::list l`, and having an
inconsistency within C++ would be worse than a C++ <-> Python
inconsistency.

It is possible to get around the copying using a
`reinterpret_borrow<list>(o)` (and this commit fixes one place, in
`embed.h`, that does so), but that seems a misuse of
`reinterpret_borrow`, which is really supposed to be just for dealing
with raw python-returned values, not `py::object`-derived wrappers which
are supposed to be higher level.

This changes the constructor of such converting types (i.e. anything
using PYBIND11_OBJECT_CVT -- `str`, `bool_`, `int_`, `float_`, `tuple`,
`dict`, `list`, `set`, `memoryview`) to reference rather than copy when
the check function passes.

It also adds an `object &&` constructor that is slightly more efficient
by avoiding an inc_ref when the check function passes.
2017-08-04 10:14:55 -04:00
Jason Rhinelander
85d63c3bcd Superclass typo fix
This didn't actually affect anything (because all the MI3 constructor
does is invoke MI2 with the same arguments anyway).
2017-07-29 03:54:25 -04:00
Jason Rhinelander
1682b67326 Simplify error_already_set
`error_already_set` is more complicated than it needs to be, partly
because it manages reference counts itself rather than using
`py::object`, and partly because it tries to do more exception clearing
than is needed.  This commit greatly simplifies it, and fixes #927.

Using `py::object` instead of `PyObject *` means we can rely on
implicit copy/move constructors.

The current logic did both a `PyErr_Clear` on deletion *and* a
`PyErr_Fetch` on creation.  I can't see how the `PyErr_Clear` on
deletion is ever useful: the `Fetch` on creation itself clears the
error, so the only way doing a `PyErr_Clear` on deletion could do
anything if is some *other* exception was raised while the
`error_already_set` object was alive--but in that case, clearing some
other exception seems wrong.  (Code that is worried about an exception
handler raising another exception would already catch a second
`error_already_set` from exception code).

The destructor itself called `clear()`, but `clear()` was a little bit
more paranoid that needed: it called `restore()` to restore the
currently captured error, but then immediately cleared it, using the
`PyErr_Restore` to release the references.  That's unnecessary: it's
valid for us to release the references manually.  This updates the code
to simply release the references on the three objects (preserving the
gil acquire).

`clear()`, however, also had the side effect of clearing the current
error, even if the current `error_already_set` didn't have a current
error (e.g. because of a previous `restore()` or `clear()` call).  I
don't really see how clearing the error here can ever actually be
useful: the only way the current error could be set is if you called
`restore()` (in which case the current stored error-related members have
already been released), or if some *other* code raised the error, in
which case `clear()` on *this* object is clearing an error for which it
shouldn't be responsible.

Neither of those seem like intentional or desirable features, and
manually requesting deletion of the stored references similarly seems
pointless, so I've just made `clear()` an empty method and marked it
deprecated.

This also fixes a minor potential issue with the destruction: it is
technically possible for `value` to be null (though this seems likely to
be rare in practice); this updates the check to look at `type` which
will always be non-null for a `Fetch`ed exception.

This also adds error_already_set round-trip throw tests to the test
suite.
2017-07-28 20:40:35 -04:00
Jason Rhinelander
abcf43d59c Convert test_exceptions to new testing style 2017-07-28 20:40:35 -04:00
Jason Rhinelander
353615f77e Make init_holder do registration, and rename to init_instance
The instance registration for offset base types fails (under macOS, with
a segfault) in the presense of virtual base types.  The issue occurs
when trying to `static_cast<Base *>(derived_ptr)` when `derived_ptr` has
been allocated (via `operator new`) but not initialized.

This commit fixes the issue by moving the addition to
`registered_instances` into `init_holder` rather than immediately after
value pointer allocation.

This also renames it to `init_instance` since it does more than holder
initialization now.  (I also further renamed `init_holder_helper` to
`init_holder` since `init_holder` isn't used anymore).

Fixes #959.
2017-07-28 20:39:33 -04:00
Jason Rhinelander
44a17e1f3d Convert test_multiple_inheritance to new style
Significant rearrangement, but no new tests added.
2017-07-28 20:39:33 -04:00