Commit Graph

572 Commits

Author SHA1 Message Date
François Becker ce9d6e2c0d Fixed typo in classes.rst (#1388)
Fixed typos (erroneous `;`) in `classes.rst`.
2018-05-07 10:18:08 -03:00
luzpaz 4b874616b2 Misc. typos (#1384)
Found via `codespell`
2018-05-06 10:54:10 -03:00
Tom de Geus a7ff616dfb Simplified example allowing more robust usage, fixed minor spelling issues 2018-05-06 10:48:54 -03:00
Wenzel Jakob f5f6618962 updated changelog for v2.2.3 2018-04-29 15:47:13 +02:00
Lori A. Burns bdbe8d0bde Enforces intel icpc >= 2017, fixes #1121 (#1363) 2018-04-29 13:48:25 +02:00
David Caron 307ea6b7fd Typo 2018-04-24 17:44:57 -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
Antony Lee 8fbb5594fd Clarify error_already_set documentation. 2018-04-09 16:25:04 -03: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
Patrik Huber 41a4fd8ae9 Fix missing word typo
I think that there's the word "for" missing for that sentence to be correct.
Please double-check that the sentence means what it's supposed to mean. :-)
2018-04-02 21:10:38 -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
Marc Schlaich ab003dbdd9 Correct VS version in FAQ 2018-03-10 14:19:31 -04:00
Tomas Babej 01fada7674 Minor typo 2018-02-27 22:46:29 -04:00
Wenzel Jakob 2d0507db43 added v2.2.2 changelog 2018-02-07 11:05:41 +01:00
luz.paz 28cb6764fc misc. typos
Found via `codespell`
2018-01-11 16:39:50 -04:00
Bruce Merry 3b265787f2 Document using atexit for module destructors on PyPy (#1169)
None of the three currently recommended approaches works on PyPy, due to
it not garbage collecting things when you want it to. Added a note with
example showing how to get interpreter shutdown callbacks using the Python
atexit module.
2017-11-24 10:19:45 -04:00
Wenzel Jakob e7d304fbc6
added citation reference (fixes #767) (#1189) 2017-11-17 18:44:20 +01: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
Unknown 0b3f44ebdf Trivial typos
Non-user facing. 
Found using `codespell -q 3`
2017-11-01 22:48:36 -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
Dean Moldovan 56613945ae Use semi-constexpr signatures on MSVC
MSCV does not allow `&typeid(T)` in constexpr contexts, but the string
part of the type signature can still be constexpr. In order to avoid
`typeid` as long as possible, `descr` is modified to collect type
information as template parameters instead of constexpr `typeid`.
The actual `std::type_info` pointers are only collected in the end,
as a `constexpr` (gcc/clang) or regular (MSVC) function call.

Not only does it significantly reduce binary size on MSVC, gcc/clang
benefit a little bit as well, since they can skip some intermediate
`std::type_info*` arrays.
2017-09-16 12:02:49 +02:00
Wenzel Jakob f94d759881 updated changelog for v2.2.1 release 2017-09-14 08:51:30 +02:00
Dean Moldovan 27680302dd Update changelog for v2.2.1 release 2017-09-13 19:04:25 +02:00
jbarlow83 9f82370e48 docs: Describe importing Python modules and Python methods (#1079)
* Expand documentation to include explicit example of py::module::import 
  where one would expect it.

* Describe how to use unbound and bound methods to class Python classes.

[skip ci]
2017-09-13 16:18:08 +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 953d2422b3 Fix a reference leak in the number converter (#1078)
Fixes #1075.

`PyNumber_Float()` and `PyNumber_Long()` return new references.
2017-09-10 16:53:02 +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 b0a0e4a23c Fix compilation with Clang on host GCC < 5 (old libstdc++) 2017-09-08 12:48:14 +02:00
Dean Moldovan 0991d7fba1 Remove deprecated placement-new constructor from docs
[skip ci]
2017-09-07 15:02:16 +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 91b42c8174 Add upgrade guide entry about stricter compile-time checks
Closes #1048, closes #1052.

[skip ci]
2017-09-04 23:01:34 +02:00
Patrik Huber 1ad2227d3c Fixed typo in docs
[skip ci]
2017-09-04 23:00:19 +02:00
Bruce Merry b490b44e34 Update documentation for keep_alive to match new implementation
PR #880 changed the implementation of keep_alive to avoid weak
references when the nurse is pybind11-registered, but the documentation
didn't get updated to match.
2017-09-01 21:38:16 +02:00
Wenzel Jakob 2fb4e9532e fix release.rst instructions for conda-forge SHA checksum
[skip ci]
2017-08-31 23:05:47 +02:00
Wenzel Jakob 8cf091a41f updated version flags for next version 2017-08-31 14:01:08 +02:00
Wenzel Jakob 2a5a5ec0a4 updated changelog.rst with release date 2017-08-31 13:58:24 +02:00
Wenzel Jakob def3c18c65 updated variables for v2.2.0 release 2017-08-31 13:56:57 +02:00
Dean Moldovan 4c5404421f Update changelog and upgrade guide
[skip ci]
2017-08-30 22:48:39 +02:00
Ivan Smirnov 5cbfda5b68 Update build commands for Linux / OS X in the docs (#907) 2017-08-30 21:58:43 +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
Dean Moldovan b8c5dbdef5 Show a deprecation warning for old-style `__init__` and `__setstate__`
The warning is shown at module initialization time (on import, not
when the functions are called). It's only visible when compiled in
debug mode.
2017-08-30 11:11:38 +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 a1041190c8 mention PR #1037 in changelog 2017-08-28 16:35:32 +02:00
Wenzel Jakob 8ed5b8ab55 make implicit conversions non-reentrant (fixes #1035) (#1037) 2017-08-28 16:34:06 +02:00
Dean Moldovan 93528f57f3 Document that type_caster requires default-constructible types
[skip ci]
2017-08-28 14:58:11 +02:00
Wenzel Jakob 5f317e60bd extended module destructor documentation (#1031) 2017-08-26 00:35:05 +02:00
Henry Schreiner 8b40505575 Utility for redirecting C++ streams to Python (#1009) 2017-08-25 02:12:43 +02:00
Matthias Hochsteger e8b5074187 Fix wrong link in changelog 2017-08-23 12:06:30 -04:00
Wenzel Jakob b12a9d67c6 mention PR #1015 in changelog 2017-08-23 16:30:56 +02:00
Wenzel Jakob 4336a7da4a support for brace initialization 2017-08-22 16:22:56 +02:00
Wenzel Jakob fb276c661f minor text edits in advanced/classes.rst (unrelated to PR) 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
Dean Moldovan 1fb9df601c Add upgrade guide to the documentation
[skip ci]
2017-08-21 01:12:45 +02:00
Dean Moldovan db46a89d96 Update changelog for v2.2.0
[skip ci]
2017-08-21 00:59:48 +02:00
Patrik Huber d265933d85 Fix typos in Eigen documentation
Fixes one small variable name typo, and two instances where `py::arg().nocopy()` is used, where I think it should be `py::arg().noconvert()` instead. Probably `nocopy()` was the old/original name for it and then it was changed.
2017-08-19 15:31:32 -04: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 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
Dean Moldovan 8665ee8100 Fix documentation build
* Doxygen needs `RECURSIVE = YES` in order to parse the `detail` subdir.

* The `-W` warnings-as-errors option for sphinx doesn't work with the
  makefile build. Switched to calling sphinx directly.

* Fix "citation [cppimport] is not referenced" warning.
2017-08-17 15:10:51 +02:00
Jason Rhinelander 97aa54fefa Compile with hidden visibility always; set via cmake property rather than compiler flag
This updates the compilation to always apply hidden visibility to
resolve the issues with default visibility causing problems under debug
compilations.  Moreover using the cmake property makes it easier for a
caller to override if absolutely needed for some reason.

For `pybind11_add_module` we use cmake to set the property; for the
targets, we append to compilation option to non-MSVC compilers.
2017-08-14 11:44:17 -04: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
EricCousineau-TRI e06077bf47 Document the requirement to explicitly initialize C++ bases (#986)
* Ensure :ref: for virtual_and_inheritance is parsed.

* Add quick blurb about __init__ with inherited types.

[skip ci]
2017-08-08 00:37:42 +02:00
Jason Rhinelander ebd6ad588b Fix boost::variant example to not forward args
boost::apply_visitor accepts its arguments by non-const lvalue
reference, which fails to bind to an rvalue reference.  Change the
example to remove the argument forwarding.
2017-08-07 15:48:49 -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
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
Jason Rhinelander abc29cad02 Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation.  This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.

Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).

Specifying a noconvert looks like one of these:

    m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
    m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
    m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting

(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).

Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument.  Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-02-03 20:18:15 -05:00
jbarlow83 40db2c757a RFC - Add documentation for strings and Unicode issues (#636)
* Add documentation for strings and Unicode issues

* More Unicode documentation on character literals and wide characters
2017-02-02 13:56:31 +01:00
Jason Rhinelander 12494525cf Minor fixes (#613)
* Minor doc syntax fix

The numpy documentation had a bad :file: reference (was using double
backticks instead of single backticks).

* Changed long-outdated "example" -> "tests" wording

The ConstructorStats internal docs still had "from example import", and
the main testing cpp file still used "example" in the module
description.
2017-01-31 17:28:29 +01:00
Jason Rhinelander 2686da8350 Add support for positional args with args/kwargs
This commit rewrites the function dispatcher code to support mixing
regular arguments with py::args/py::kwargs arguments.  It also
simplifies the argument loader noticeably as it no longer has to worry
about args/kwargs: all of that is now sorted out in the dispatcher,
which now simply appends a tuple/dict if the function takes
py::args/py::kwargs, then passes all the arguments in a vector.

When the argument loader hit a py::args or py::kwargs, it doesn't do
anything special: it just calls the appropriate type_caster just like it
does for any other argument (thus removing the previous special cases
for args/kwargs).

Switching to passing arguments in a single std::vector instead of a pair
of tuples also makes things simpler, both in the dispatch and the
argument_loader: since this argument list is strictly pybind-internal
(i.e. it never goes to Python) we have no particular reason to use a
Python tuple here.

Some (intentional) restrictions:
- you may not bind a function that has args/kwargs somewhere other than
  the end (this somewhat matches Python, and keeps the dispatch code a
  little cleaner by being able to not worry about where to inject the
  args/kwargs in the argument list).
- If you specify an argument both positionally and via a keyword
  argument, you get a TypeError alerting you to this (as you do in
  Python).
2017-01-31 17:24:41 +01:00
Dustin Spicuzza 18d7df5efd Documentation: explicitly call out that the GIL is held (#615) 2017-01-31 17:06:13 +01:00
Dean Moldovan ec009a7ca2 Improve custom holder support (#607)
* Abstract away some holder functionality (resolve #585)

Custom holder types which don't have `.get()` can select the correct
function to call by specializing `holder_traits`.

* Add support for move-only holders (fix #605)
2017-01-31 17:05:44 +01:00
Jason Rhinelander f7f5bc8e37 Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation

The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't.  The changes the
documentation and docs example to make it clear that you need to "call"
the macro.

* Add satisfies_{all,any,none}_of<T, Preds>

`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.

* Give better error message for non-POD dtype attempts

If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.

This adds a static_assert for such cases.

It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.

* Prefix macros with PYBIND11_

numpy.h uses unprefixed macros, which seems undesirable.  This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).

* Add long double support

This adds long double and std::complex<long double> support for numpy
arrays.

This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).

In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 17:00:15 +01:00
Dean Moldovan 57a9bbc6c7 Automate generation of reference docs with doxygen and breathe (#598)
* Make 'any' the default markup role for Sphinx docs

* Automate generation of reference docs with doxygen and breathe

* Improve reference docs coverage
2017-01-31 16:54:08 +01:00
jbarlow83 7830e8509f Docs: minor clarifications (#590)
* Some clarifications to section on virtual fns

Primarily, I made it clear that PYBIND11_OVERLOAD_PURE_NAME is not "useful" but required in renaming situations. Also clarified that one should not bind to the trampoline helper class which I found tempting since it seems more explicit.

* Remove :emphasize-lines: from cpp block, seems to suppress formatting

* docs: emphasize default policy, clarify keep_alive

Emphasize the default return value policy since this statement is hidden in a wall of text. 

Add a hint that call policies are probably required for container objects.
2017-01-13 11:17:29 +01:00
myd7349 9b815ad2e9 Docs: Fix several errors of examples from the doc (#592)
* [Doc] Fix several errors of examples from the doc

* Add missing operator def.

* Added missing `()`

* Add missing `namespace`.
2017-01-13 11:15:52 +01:00
Wenzel Jakob a9730be73c use -x flag to strip shared libraries on OSX (fixes #595) 2017-01-06 14:20:26 +01:00
Wenzel Jakob f8dafe908e changelog for 2.0.1 release 2017-01-04 15:09:49 +01:00
Wenzel Jakob 2723a38820 minor setup.py updates 2017-01-01 17:14:27 +01:00
Wenzel Jakob fb4e1047e4 begin work on v2.1.0 2017-01-01 14:29:40 +01:00
Wenzel Jakob e33ef9c20d v2.0.0 release 2017-01-01 13:56:37 +01:00
Wenzel Jakob 401008163a updated release instructions 2016-12-29 23:44:48 +01:00
Michael König f331843b39 Make non-ancient version of GCC explicit in documentation (it means 4.8+) (#575) 2016-12-28 12:10:11 +01:00
Wenzel Jakob f3de2d5521 reference binder project from documentation 2016-12-26 13:54:50 +01:00
Wenzel Jakob 1805c3489f updated LOC values in README.md and intro.rst 2016-12-26 13:54:50 +01:00
Wenzel Jakob ed52f4664c updated changelog 2016-12-26 13:54:50 +01:00
Wenzel Jakob 3c79671112 a few more minor v2.0.0-rc1 related changes 2016-12-23 16:19:36 +01:00
Wenzel Jakob d3549d6027 added changelog for v2.0.0-rc1 2016-12-23 16:01:19 +01:00
Jason Rhinelander 05920e363e Change compilation/test target back to `check` (#566) 2016-12-19 17:33:02 +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
Wenzel Jakob 003a9eba59 fixed pypy minimum version 2016-12-18 17:08:13 +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
Lori A. Burns f4b81b36bf reflow some docs paragraphs 2016-12-13 21:44:19 +01:00
Lori A. Burns 5cafc99884 add CMake exported interface library and Config detection file 2016-12-13 21:44:19 +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
Wenzel Jakob 8fadade225 add valarray to documentation, update docutils on travis 2016-12-09 16:08:16 +01:00
Dean Moldovan 4e959c9af4 Add syntax sugar for resolving overloaded functions (#541) 2016-12-08 11:07:52 +01:00
Dean Moldovan ab90ec6ce9 Allow references to objects held by smart pointers (#533) 2016-12-07 02:36:44 +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
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
Wenzel Jakob 2fb5f1d0c3 added message about recursion limits 2016-11-16 17:37:10 +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
Wenzel Jakob 45e6e6f6eb add note about custom type casters (fixes #480) 2016-11-04 11:06:22 +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
Ivan Smirnov f95fda0eb2 Add docs re: shared data API 2016-11-03 09:35:05 +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
Wenzel Jakob 6ba98650e2 a bit of work on the new documentation structure 2016-10-24 23:48:20 +02:00
Jason Rhinelander fb7c9fd326 Remove obsolete example reference (#457)
* Remove obsolete example reference
* Make example fully-working (except for #includes)

Fixes #456.
2016-10-22 18:54:33 +02:00
Dean Moldovan 5d28dd1194 Support std::shared_ptr holder type out of the box
With this there is no more need for manual user declarations like
`PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)`. Existing ones
will still compile without error -- they will just be ignored silently.

Resolves #446.
2016-10-20 16:19:58 +02:00
Dean Moldovan f0b0df58a9 Directly compare 3 ways of moving data between C++ and Python 2016-10-20 15:21:34 +02:00
Dean Moldovan 67b52d808e Reorganize documentation 2016-10-20 15:21:34 +02:00
Dean Moldovan 9273af4f92 Document dynamic attributes 2016-10-14 01:16:40 +02:00
Wenzel Jakob 632dee1e11 Merge pull request #356 from TrentHouliston/master
Add in casts for c++11s chrono classes to pythons datetime
2016-09-27 17:58:34 +02:00
Trent Houliston 10a6a90738 Redo documentation to make it easier to read 2016-09-28 01:01:59 +10:00
Dean Moldovan 242b146a51 Extend attribute and item accessor interface using object_api 2016-09-23 02:00:01 +02:00
Jason Rhinelander 20ef62656f Fix minor documentation spelling mistakes 2016-09-21 13:39:02 -04:00
Wenzel Jakob d4285a6dda ..one more typo 2016-09-21 19:30:23 +02:00
Wenzel Jakob 514371ebec typo fixes (spotted by @TheGhostHuCodes) 2016-09-21 19:29:19 +02:00
Wenzel Jakob 8e5dceb6a6 Multiple inheritance support 2016-09-19 13:45:31 +02:00
Wenzel Jakob bad589a477 deprecated py::base<>, added a macro for improved readability 2016-09-19 13:43:47 +02:00
Jason Rhinelander b3794f1087 Added py::register_exception for simple case (#296)
The custom exception handling added in PR #273 is robust, but is overly
complex for declaring the most common simple C++ -> Python exception
mapping that needs only to copy `what()`.  This add a simpler
`py::register_exception<CppExp>(module, "PyExp");` function that greatly
simplifies the common basic case of translation of a simple CppException
into a simple PythonException, while not removing the more advanced
capabilities of defining custom exception handlers.
2016-09-16 08:04:15 +02:00
Trent Houliston 2f597687e7 Changed non system clocks to be time deltas
Allowed durations and non system clocks to be set from floats.
2016-09-13 20:40:28 +10:00
Trent Houliston 352149e892 Refactor the chrono cast functions into chrono.h.
Add unit tests and documentation for the chrono cast.
2016-09-13 19:58:05 +10:00
Jason Rhinelander 7dfb932e70 Update OVERLOAD macros to support ref/ptr return type overloads
This adds a static local variable (in dead code unless actually needed)
in the overload code that is used for storage if the overload is for
some convert-by-value type (such as numeric values or std::string).

This has limitations (as written up in the advanced doc), but is better
than simply not being able to overload reference or pointer methods.
2016-09-11 01:21:53 -04:00
Jason Rhinelander 6eca083e4c Fix doc typo
"trampoline" is doubled in the first sentence.
2016-09-11 01:16:19 -04:00
Wenzel Jakob 1f2e417d8c Merge pull request #403 from jagerman/alias-initialization
Implement py::init_alias<>() constructors
2016-09-10 16:12:19 +09:00
Wenzel Jakob 382484ae56 operators should return NotImplemented given unsupported input (fixes #393) 2016-09-10 15:34:26 +09:00
Jason Rhinelander ec62d977c4 Implement py::init_alias<>() constructors
This commit adds support for forcing alias type initialization by
defining constructors with `py::init_alias<arg1, arg2>()` instead of
`py::init<arg1, arg2>()`.  Currently py::init<> only results in Alias
initialization if the type is extended in python, or the given
arguments can't be used to construct the base type, but can be used to
construct the alias.  py::init_alias<>, in contrast, always invokes the
constructor of the alias type.

It looks like this was already the intention of
`py::detail::init_alias`, which was forward-declared in
86d825f330, but was apparently never
finished: despite the existance of a .def method accepting it, the
`detail::init_alias` class isn't actually defined anywhere.

This commit completes the feature (or possibly repurposes it), allowing
declaration of classes that will always initialize the trampoline which
is (as I argued in #397) sometimes useful.
2016-09-09 03:04:09 -04:00
Jason Rhinelander 6b52c838d7 Allow passing base types as a template parameter
This allows a slightly cleaner base type specification of:

    py::class_<Type, Base>("Type")

as an alternative to

    py::class_<Type>("Type", py::base<Base>())

As with the other template parameters, the order relative to the holder
or trampoline types doesn't matter.

This also includes a compile-time assertion failure if attempting to
specify more than one base class (but is easily extendible to support
multiple inheritance, someday, by updating the class_selector::set_bases
function to set multiple bases).
2016-09-06 20:34:24 -04:00
Jason Rhinelander 5fffe200e3 Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.

This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options.  It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively.  (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively).  If any unmatched template arguments are provided, a
static assertion fails.

What this means is that you can specify or omit the arguments in any
order:

    py::class_<A, PyA> c1(m, "A");
    py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
    py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");

It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 12:22:13 -04:00
Dean Moldovan 625bd48a91 Document calling function with keyword arguments from C++ 2016-09-06 16:41:50 +02:00
Wenzel Jakob 6f017cf658 basics.rst: minor table update for Eigen types 2016-09-06 14:13:35 +09:00
Wenzel Jakob 48ce0727e4 added docs for custom type casters (fixes #298) 2016-09-06 14:13:22 +09:00
Wenzel Jakob fe34241e50 minor doc & style fixes 2016-09-06 13:02:29 +09:00
Sergey Lyskov 7520418e26 Adding bind_map 2016-09-05 17:11:16 -04:00
Wenzel Jakob 70f5a4dc8b minor: added error message to faq 2016-09-05 17:19:18 +09:00
Jason Rhinelander 64830e3333 Doc fix for OVERLOAD*_NAME macros
The documentation says the string-valued python function name goes
after the C++ function, but it actually goes before it.
2016-08-29 16:58:59 -04:00
Wenzel Jakob 5e4e477b8b minor fixes to PR #368 2016-08-28 02:03:15 +02:00
Nickolai Belakovski 6333825350 Added support for exposing classes with private destructors and corresponding documentation 2016-08-27 15:09:15 -07:00
Ivan Smirnov 606160ed68 Update the changelog re: generalized iterators 2016-08-24 23:32:13 +01:00
Wenzel Jakob faec30c4db Merge pull request #321 from dean0x7d/pytest
Port test suite to pytest
2016-08-22 13:02:27 +02:00
Wenzel Jakob bf099587cd documentation clarifications (fixes #346) 2016-08-22 12:52:02 +02:00
Dean Moldovan ec0d38ef25 Update the docs to reflect the new test structure
Test compilation instructions for Windows were changed to use the
`cmake --build` command line invocation which should be easier than
manually setting up using the CMake GUI and Visual Studio.
2016-08-19 13:32:01 +02:00
Wenzel Jakob 192eb88475 ..mention in benchmark docs as well 2016-08-19 09:38:14 +02:00
Wenzel Jakob 68b193e3f2 mention pyrosetta stats 2016-08-19 09:32:58 +02:00
Wenzel Jakob 0b63231bae minor doc touchups 2016-08-18 10:58:21 +02:00
Glen Walker f45bb585c3 Support keep_alive where nurse may be None
For example keep_alive<0,1>() should work where the return value may sometimes be None. At present a "Could not allocate weak reference!" exception is thrown.
Update documentation to clarify behaviour of keep_alive when nurse is None or does not support weak references.
2016-08-18 09:09:41 +12:00
Dean Moldovan aebca12bb9 Fix sphinx doc missing code blocks and warnings
The missing empty line after `.. code-block::` resulted in incorrectly
parsed restructuredtext (sphinx warnings) and the code blocks were not
generated in the html output.

The `exclude_patterns` change just silences the orphaned file warning.

[ci skip]
2016-08-16 01:30:58 +02:00
Ivan Smirnov 6715736936 Add handle::repr() method 2016-08-14 13:43:31 +01:00
Ivan Smirnov bccbc10a65 Update changelog and authors 2016-08-13 21:17:26 +01:00
Ivan Smirnov b65185906d Update the docs to use the new array ctor 2016-08-13 13:28:56 +01:00
Ivan Smirnov 5412a05cf0 Rename PYBIND11_DTYPE to PYBIND11_NUMPY_DTYPE 2016-08-13 12:43:16 +01:00
Ivan Smirnov 5afe9df30a Minor fix in the docs 2016-08-13 12:43:16 +01:00
Ivan Smirnov 223afe37fa Add documentation re: PYBIND11_DTYPE macro 2016-08-13 12:43:16 +01:00
Ivan Smirnov 5e71e17bdf Make changes to format_descriptor backwards-compat
The format strings that are known at compile time are now accessible
via both ::value and ::format(), and format strings for everything
else is accessible via ::format(). This makes it backwards compatible.
2016-08-13 12:43:16 +01:00
Ivan Smirnov 42ad328481 Change format_descriptor::value to a static func 2016-08-13 12:43:16 +01:00
Jason Rhinelander 5aa85be26e Added pybind11::make_key_iterator for map iteration
This allows exposing a dict-like interface to python code, allowing
iteration over keys via:

    for k in custommapping:
        ...

while still allowing iteration over pairs, so that you can also
implement 'dict.items()' functionality which returns a pair iterator,
allowing:

    for k, v in custommapping.items():
        ...

example-sequences-and-iterators is updated with a custom class providing
both types of iteration.
2016-08-11 21:22:05 -04:00
Jason Rhinelander f2ecd8927e Implement reference_internal with a keep_alive
reference_internal requires an `instance` field to track the returned
reference's parent, but that's just a duplication of what
keep_alive<0,1> does, so use a keep alive to do this to eliminate the
duplication.
2016-08-10 12:08:04 -04:00
Jason Rhinelander efc2aa7ee7 Removed obsolete documentation about duplicate address problems
It no longer applies since instances are now identified by both address
and type.
2016-08-10 11:38:33 -04:00
Jason Rhinelander d6c365bcfa virtual + inheritance example: remove multiple inheritance approach
It was already pretty badly intrusive, but it also appears to make MSVC
segfault.  Rather than investigating and fixing it, it's easier to just
remove it.
2016-08-05 18:03:06 -04:00
Jason Rhinelander 0ca96e2915 Added advanced doc section on virtual methods + inheritance
As discussed in #320.

The adds a documentation block that mentions that the trampoline classes
must provide overrides for both the classes' own virtual methods *and*
any inherited virtual methods.  It also provides a templated solution to
avoiding method duplication.

The example includes a third method (only mentioned in the "see also"
section of the documentation addition), using multiple inheritance.
While this approach works, and avoids code generation in deep
hierarchies, it is intrusive by requiring that the wrapped classes use
virtual inheritance, which itself is more instrusive if any of the
virtual base classes need anything other than default constructors.  As
per the discussion in #320, it is kept as an example, but not suggested
in the documentation.
2016-08-05 18:02:37 -04:00
Jason Rhinelander b68d8fc2c5 *Really* fix enumeration indices 2016-08-04 16:39:30 -04:00
Jason Rhinelander 38d5b4565c Fixed enumeration indices 2016-08-04 16:36:16 -04:00
Jason Rhinelander 9ffb3dda5f Eigen support for special matrix objects
Functions returning specialized Eigen matrices like Eigen::DiagonalMatrix and
Eigen::SelfAdjointView--which inherit from EigenBase but not
DenseBase--isn't currently allowed; such classes are explicitly copyable
into a Matrix (by definition), and so we can support functions that
return them by copying the value into a Matrix then casting that
resulting dense Matrix into a numpy.ndarray.  This commit does exactly
that.
2016-08-04 15:24:41 -04:00
Wenzel Jakob 3764e28475 added note about args/kwargs limitation 2016-08-01 23:34:48 +02:00
Wenzel Jakob f38f359f96 documentation fix (fixes #290) 2016-07-19 17:48:42 +02:00
Jason Rhinelander 3e2e44f53f Updated advanced.rst example references 2016-07-18 17:03:37 -04:00
Wenzel Jakob fb6aed2157 return value policy clarifications 2016-07-18 20:29:53 +02:00
Wenzel Jakob a720a6046e updated changelog with v1.8.1, updated release instructions 2016-07-12 18:03:17 +02:00
Wenzel Jakob c47d498c35 fix rare GC issue during type creation (fixes #277) 2016-07-11 23:41:15 +02:00
Wenzel Jakob 58ec1caa9b updated README and changelog 2016-07-11 23:39:39 +02:00
Wenzel Jakob 3c6ada3a48 Merge pull request #273 from lsst-dm/master
Add support for user defined exception translators
2016-07-11 23:38:21 +02:00
Pim Schellart 5a7d17ff16 Add support for user defined exception translators 2016-07-11 17:33:04 -04:00
Wenzel Jakob e6b2f75949 updated changelog 2016-07-10 10:54:46 +02:00
Wenzel Jakob 954b7932fe avoid C++ -> Python -> C++ overheads when passing around function objects 2016-07-10 10:44:44 +02:00
Wenzel Jakob 0d3fc3566a complete rewrite of eval/exec patch 2016-07-08 10:52:10 +02:00
Klemens Morgenstern c6ad2c4993 added exec functions 2016-07-08 10:05:24 +02:00
Wenzel Jakob 3eeea6fa61 docs: point out limitations of implicit conversions 2016-06-30 18:10:28 +02:00
Wenzel Jakob f53e300fbd doc updates 2016-06-30 14:59:23 +02:00
Wenzel Jakob 09e22b4a17 Merge pull request #255 from nafur/patch-1
Added warning about same-address-optimization
2016-06-30 14:48:29 +02:00
Wenzel Jakob 4626b5a4af updated limitations section 2016-06-30 14:46:11 +02:00
nafur 717df75237 Added warning about same-address-optimization
See https://github.com/pybind/pybind11/issues/254
2016-06-28 18:07:11 +02:00
Wenzel Jakob 37e1f61f54 allow passing a 'return value policy' to handle::operator() 2016-06-22 14:29:13 +02:00
Wenzel Jakob f88af0c127 clarification on static properties (fixes #248) 2016-06-22 13:52:31 +02:00
Brad Harmon 835fc06ca4 Add callback examples with named parameters 2016-06-16 13:19:15 -05:00
Wenzel Jakob 663513cf23 release process clarifications 2016-06-14 16:08:31 +02:00
Wenzel Jakob f85c52901e starting to work on release v1.9 2016-06-14 15:24:47 +02:00
Wenzel Jakob f950215046 note about semver policy 2016-06-14 15:02:07 +02:00
Wenzel Jakob 1cbe7ef2ac changelog update 2016-06-14 14:55:10 +02:00
Dean Moldovan b3eadfa595 Update docs with _a suffix notation for named arguments 2016-06-03 23:52:56 +02:00
Wenzel Jakob f600c1d899 updated FAQ section on Python detection 2016-06-03 14:47:54 +02:00
Wenzel Jakob ca8dc08a66 updated pbtest link 2016-06-03 14:24:17 +02:00
Wenzel Jakob aa79af09f6 updated cmake example link 2016-06-03 12:23:24 +02:00
Wenzel Jakob 9bb97c1b96 docs: added a general note about macro usage 2016-06-03 11:19:50 +02:00
Wenzel Jakob 99279f7107 docs: switched lexer for python console snippets to 'pycon' 2016-06-03 11:19:50 +02:00
Wenzel Jakob 38d8b8cfe2 don't allow registering a class twice (fixes #218) 2016-05-31 09:53:28 +02:00
Wenzel Jakob 1503d2fb50 Merge pull request #207 from dean0x7d/cmake
Simplify CMake build using add_subdirectory
2016-05-29 12:29:36 +02:00
Dean Moldovan 24ddf4b3f1 Update CMake build documentation 2016-05-27 00:11:52 +02:00