Commit Graph

306 Commits

Author SHA1 Message Date
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
Dustin Spicuzza 7c0e2c247b Document automatic upcasting of polymorphic types (#654)
Resolves #645.
2017-07-23 03:36:08 +02:00
Dean Moldovan 0bc272b2e9 Move tests from short translation units into their logical parents 2017-06-27 10:38:41 +02:00
Dean Moldovan 83e328f58c Split test_python_types.cpp into builtin_casters, stl and pytypes 2017-06-27 10:38:41 +02:00
Dean Moldovan 2bde61500d Fix invalid reference definition in string conversion docs
[skip ci]
2017-06-25 17:35:44 +02:00
Jason Rhinelander f42af24a7d Support std::string_view when compiled under C++17 2017-06-24 03:24:56 -03:00
Jason Rhinelander 220a77f5cd Endian wording fix 2017-06-24 03:24:56 -03:00
Jason Rhinelander aee409dc8d Fix strings.rst style
Wrapped long lines and removed a few trailing spaces.
2017-06-24 03:24:56 -03:00
Ian Bell 28f3df7ff3 Fix typo in embedding.rst 2017-06-15 10:37:28 -03:00
Jason Rhinelander e45c211497 Support multiple inheritance from python
This commit allows multiple inheritance of pybind11 classes from
Python, e.g.

    class MyType(Base1, Base2):
        def __init__(self):
            Base1.__init__(self)
            Base2.__init__(self)

where Base1 and Base2 are pybind11-exported classes.

This requires collapsing the various builtin base objects
(pybind11_object_56, ...) introduced in 2.1 into a single
pybind11_object of a fixed size; this fixed size object allocates enough
space to contain either a simple object (one base class & small* holder
instance), or a pointer to a new allocation that can contain an
arbitrary number of base classes and holders, with holder size
unrestricted.

* "small" here means having a sizeof() of at most 2 pointers, which is
enough to fit unique_ptr (sizeof is 1 ptr) and shared_ptr (sizeof is 2
ptrs).

To minimize the performance impact, this repurposes
`internals::registered_types_py` to store a vector of pybind-registered
base types.  For direct-use pybind types (e.g. the `PyA` for a C++ `A`)
this is simply storing the same thing as before, but now in a vector;
for Python-side inherited types, the map lets us avoid having to do a
base class traversal as long as we've seen the class before.  The
change to vector is needed for multiple inheritance: Python types
inheriting from multiple registered bases have one entry per base.
2017-06-12 09:56:55 -03:00
Matthew Chan 6223b18cea Update basics.rst
Fix spelling
2017-06-08 16:42:44 -03:00
Dean Moldovan 8f6c129689 Fix CMake example code in embedding docs
[skip ci]
2017-05-31 13:49:27 +02:00
Dean Moldovan 443ab5946b Replace PYBIND11_PLUGIN with PYBIND11_MODULE
This commit also adds `doc()` to `object_api` as a shortcut for the
`attr("__doc__")` accessor.

The module macro changes from:
```c++
PYBIND11_PLUGIN(example) {
    pybind11::module m("example", "pybind11 example plugin");
    m.def("add", [](int a, int b) { return a + b; });
    return m.ptr();
}
```

to:

```c++
PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin";
    m.def("add", [](int a, int b) { return a + b; });
}
```

Using the old macro results in a deprecation warning. The warning
actually points to the `pybind11_init` function (since attributes
don't bind to macros), but the message should be quite clear:
"PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE".
2017-05-29 03:21:19 +02:00
Dean Moldovan 6d2411f1ac Add tutorial page for embedding the interpreter 2017-05-28 02:12:24 +02:00
Dean Moldovan 22c413b196 Add C++ interface for the Python interpreter 2017-05-28 02:12:24 +02:00
Jason Rhinelander 4f9ee6e430 Fix exception reference error
:exc: isn't valid.
2017-05-26 23:20:48 -04:00
chenzy 39b9e04be8 Correct error in numpy.rst 2017-05-26 21:24:53 -04:00
Jason Rhinelander f3ce00eaed vectorize: pass-through of non-vectorizable args
This extends py::vectorize to automatically pass through
non-vectorizable arguments.  This removes the need for the documented
"explicitly exclude an argument" workaround.

Vectorization now applies to arithmetic, std::complex, and POD types,
passed as plain value or by const lvalue reference (previously only
pass-by-value types were supported).  Non-const lvalue references and
any other types are passed through as-is.

Functions with rvalue reference arguments (whether vectorizable or not)
are explicitly prohibited: an rvalue reference is inherently not
something that can be passed multiple times and is thus unsuitable to
being in a vectorized function.

The vectorize returned value is also now more sensitive to inputs:
previously it would return by value when all inputs are of size 1; this
is now amended to having all inputs of size 1 *and* 0 dimensions.  Thus
if you pass in, for example, [[1]], you get back a 1x1, 2D array, while
previously you got back just the resulting single value.

Vectorization of member function specializations is now also supported
via `py::vectorize(&Class::method)`; this required passthrough support
for the initial object pointer on the wrapping function pointer.
2017-05-24 20:43:41 -04:00
Jason Rhinelander 4e1e4a580e Allow py::arg().none(false) argument attribute
This attribute lets you disable (or explicitly enable) passing None to
an argument that otherwise would allow it by accepting
a value by raw pointer or shared_ptr.
2017-05-24 13:10:57 -04:00
Bruce Merry b82c0f0a2d Allow std::complex field with PYBIND11_NUMPY_DTYPE (#831)
This exposed a few underlying issues:

1. is_pod_struct was too strict to allow this. I've relaxed it to
require only trivially copyable and standard layout, rather than POD
(which additionally requires a trivial constructor, which std::complex
violates).

2. format_descriptor<std::complex<T>>::format() returned numpy format
strings instead of PEP3118 format strings, but register_dtype
feeds format codes of its fields to _dtype_from_pep3118. I've changed it
to return PEP3118 format codes. format_descriptor is a public type, so
this may be considered an incompatible change.

3. register_structured_dtype tried to be smart about whether to mark
fields as unaligned (with ^). However, it's examining the C++ alignment,
rather than what numpy (or possibly PEP3118) thinks the alignment should
be. For complex values those are different. I've made it mark all fields
as ^ unconditionally, which should always be safe even if they are
aligned, because we explicitly mark the padding.
2017-05-10 11:36:24 +02:00
Bruce Merry 8e0d832c7d Support arrays inside PYBIND11_NUMPY_DTYPE (#832)
Resolves #800.

Both C++ arrays and std::array are supported, including mixtures like
std::array<int, 2>[4]. In a multi-dimensional array of char, the last
dimension is used to construct a numpy string type.
2017-05-10 10:21:01 +02:00
Jason Rhinelander 77710ff01c Make PYBIND11_CPP_STANDARD work under MSVC
Under MSVC we were ignoring PYBIND11_CPP_STANDARD and simply not
passing any standard (which makes MSVC default to its C++14 mode).

MSVC 2015u3 added the `/std:c++14` and `/std:c++latest` flags; the
latter, under MSVC 2017, enables some C++17 features (such as
`std::optional` and `std::variant`), so it is something we need to
start supporting under MSVC.

This makes the PYBIND11_CPP_STANDARD cmake variable work under MSVC,
defaulting it to /std:c++14 (matching the default -std=c++14 for
non-MSVC).

It also adds a new appveyor test running under MSVC 2017 with
/std:c++latest, which runs (and passes) the
`std::optional`/`std::variant` tests.

Also updated the documentation to clarify the c++ flags and add show
MSVC flag examples.
2017-05-09 16:41:47 -04:00
Dean Moldovan 076c738641 Add py::exec() as a shortcut for py::eval<py::eval_statements>() 2017-05-08 20:46:16 +02:00
Cris Luengo 30d43c4992 Now `shape`, `size`, `ndims` and `itemsize` are also signed integers. 2017-05-08 01:50:21 +02:00
Jason Rhinelander b68959e822 Use numpy rather than Eigen for copying
We're current copy by creating an Eigen::Map into the input numpy
array, then assigning that to the basic eigen type, effectively having
Eigen do the copy.  That doesn't work for negative strides, though:
Eigen doesn't allow them.

This commit makes numpy do the copying instead by allocating the eigen
type, then having numpy copy from the input array into a numpy reference
into the eigen object's data.  This also saves a copy when type
conversion is required: numpy can do the conversion on-the-fly as part
of the copy.

Finally this commit also makes non-reference parameters respect the
convert flag, declining the load when called in a noconvert pass with a
convertible, but non-array input or an array with the wrong dtype.
2017-05-08 01:50:21 +02:00
Cris Luengo d400f60c96 Python buffer objects can have negative strides. 2017-05-08 01:50:21 +02:00
Dean Moldovan 4ffa76ec56 Add type caster for std::variant and other variant-like classes 2017-04-29 17:31:30 +02:00
Wenzel Jakob db200955b9 changelog for v2.1.1 2017-04-07 02:08:29 +02: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
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 0d92938f74 minor style fix 2017-03-22 22:52:29 +01:00
Wenzel Jakob d405b1b3a4 updated version information for v2.2 development 2017-03-22 22:20:07 +01:00
Wenzel Jakob 62e5fef09e Changelog for v2.1.0 (#759) 2017-03-22 22:07:45 +01: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
Wenzel Jakob ab26259c87 added note about trailing commas (fixes #593) 2017-03-22 21:39:19 +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 b7017c3dad Fix readthedocs build (#721)
RTD updated their build environment which broke the 1.8.14.dev build of
doxygen that we were using. The update also breaks the conda-forge build
of 1.8.13 (but that version has other issues).

Luckily, the RTD update did bring their doxygen version up to 1.8.11
which is enough to parse the C++11 code we need (ref qualifiers) and it
also avoids the segfault found in 1.8.13.

Since we're using the native doxygen, conda isn't required anymore and
we can simplify the RTD configuration.

[skip ci]
2017-03-12 22:36:48 +01:00
Matthieu Bec af936e1987 Expose enum_ entries as "__members__" read-only property. Getters get a copy. 2017-03-03 08:45:50 -08: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
Dean Moldovan dd01665e5a Enable static properties (py::metaclass) by default
Now that only one shared metaclass is ever allocated, it's extremely
cheap to enable it for all pybind11 types.

* Deprecate the default py::metaclass() since it's not needed anymore.
* Allow users to specify a custom metaclass via py::metaclass(handle).
2017-02-23 15:45:26 +01:00
Dean Moldovan a3f4a02cf8 Minor docs build maintenance (#692)
* Switch breathe to stable releases. It was previously pulling directly
  from master because a required bugfix was not in a stable release yet.

* Force update sphinx and RTD theme. When using conda, readthedocs pins
  sphinx==1.3.5 and sphinx_rtd_theme==0.1.7, which is a bit older than
  the ones used in the RTD regular (non-conda) build. The newer theme
  has nicer sidebar navigation (4-level depth vs. only 2-level on the
  older version). Note that the python==3.5 requirement must stay
  because RTD still installs the older sphinx at one point which isn't
  available with Python 3.6.

[skip ci]
2017-02-23 08:57:25 +01:00
Wenzel Jakob baec23c2d4 minor stl caster clarifications 2017-02-17 12:59:32 +01:00
thorink e72eaa47d2 changed return_value:: to return_value_policy:: (#672)
* changed return_value:: to return_value_policy::

* Update functions.rst
2017-02-17 12:57:39 +01:00
Dean Moldovan cec052b5c5 Fix readthedocs build
Fixes #667

The sphinx version is pinned by readthedocs, but sphinx 1.3.5 is not
available with conda python 3.6. The workaround is to pin the python
version to 3.5 (it doesn't really matter for the docs build).
2017-02-14 11:39:03 +01:00
Jason Rhinelander 11a337f16f Unicode fixes and docs (#624)
* Propagate unicode conversion failure

If returning a std::string with invalid utf-8 data, we currently fail
with an uninformative TypeError instead of propagating the
UnicodeDecodeError that Python sets on failure.

* Add support for u16/u32strings and literals

This adds support for wchar{16,32}_t character literals and the
associated std::u{16,32}string types.  It also folds the
character/string conversion into a single type_caster template, since
the type casters for string and wstring were mostly the same anyway.

* Added too-long and too-big character conversion errors

With this commit, when casting to a single character, as opposed to a
C-style string, we make sure the input wasn't a multi-character string
or a single character with codepoint too large for the character type.

This also changes the character cast op to CharT instead of CharT& (we
need to be able to return a temporary decoded char value, but also
because there's little gained by bothering with an lvalue return here).

Finally it changes the char caster to 'has-a-string-caster' instead of
'is-a-string-caster' because, with the cast_op change above, there's
nothing at all gained from inheritance.  This also lets us remove the
`success` from the string caster (which was only there for the char
caster) into the char caster itself.  (I also renamed it to 'none' and
inverted its value to better reflect its purpose).  The None -> nullptr
loading also now takes place only under a `convert = true` load pass.
Although it's unlikely that a function taking a char also has overloads
that can take a None, it seems marginally more correct to treat it as a
conversion.

This commit simplifies the size assumptions about character sizes with
static_asserts to back them up.
2017-02-14 11:08:19 +01:00
Wenzel Jakob 6fa316d259 Merge pull request #643 from jagerman/two-pass-dispatch
Prefer non-converting argument overloads
2017-02-05 23:51:50 +01:00
Wenzel Jakob 18e34cb2e6 Merge pull request #634 from jagerman/noconvert-arguments
Add support for non-converting arguments
2017-02-05 23:51:38 +01:00
Jason Rhinelander e550589b42 Prefer non-converting argument overloads
This changes the function dispatching code for overloaded functions into
a two-pass procedure where we first try all overloads with
`convert=false` for all arguments.  If no function calls succeeds in the
first pass, we then try a second pass where we allow arguments to have
`convert=true` (unless, of course, the argument was explicitly specified
with `py::arg().noconvert()`).

For non-overloaded methods, the two-pass procedure is skipped (we just
make the overload-allowed call).  The second pass is also skipped if it
would result in the same thing (i.e. where all arguments are
`.noconvert()` arguments).
2017-02-03 20:47:17 -05:00