Commit Graph

531 Commits

Author SHA1 Message Date
Boris Staletic 441e777040
Use new style __init__ in numpy docs (#2316) 2020-07-23 16:03:55 +02:00
Henry Schreiner d8c7ee00a6
ci: GHA basic format & pre-commit (#2309) 2020-07-20 13:35:21 -04:00
Kota Yamaguchi e248869893
Fix undefined memoryview format (#2223)
* Fix undefined memoryview format

* Add missing <algorithm> header

* Add workaround for py27 array compatibility

* Workaround py27 memoryview behavior

* Fix memoryview constructor from buffer_info

* Workaround PyMemoryView_FromMemory availability in py27

* Fix up memoryview tests

* Update memoryview test from buffer to check signedness

* Use static factory method to create memoryview

* Remove ndim arg from memoryview::frombuffer and add tests

* Allow ndim=0 memoryview and documentation fixup

* Use void* to align to frombuffer method signature

* Add const variants of frombuffer and frommemory

* Add memory view section in doc

* Fix docs

* Add test for null buffer

* Workaround py27 nullptr behavior in test

* Rename frombuffer to from_buffer
2020-07-15 08:50:43 -07:00
Yannick Jadoul 964ab956e0
Fix DeprecationWarning about 'invalid escape sequence' in tools/docs Python scripts (#2281) 2020-07-10 16:30:44 +02:00
Dustin Spicuzza 1b0bf352fa
Throw TypeError when subclasses forget to call __init__ (#2152)
- Fixes #2103
2020-07-07 12:04:06 +02:00
Wenzel Jakob fc3a4490b8 Minor clarification (@AntoinePrv, #2083) 2020-07-01 00:29:55 +02:00
Guilherme Dantas 8908552dfc typo 2020-07-01 00:12:33 +02:00
Lin Hsu d031efe788 Typo 2020-07-01 00:08:05 +02:00
Matthijs van der Burgh b524008967
Deepcopy documentation (#2242)
* (docs) convert note to real note

* (docs) Add information about (deep)copy
2020-06-10 13:30:41 +02:00
Wenzel Jakob a54eab92d2 Revert "Change __init__(self) to __new__(cls)"
This reverts commit 9ed8b44033.
2020-04-26 22:53:50 +02:00
Dustin Spicuzza 2c4cd8419d Add AutoWIG to list of binding generators (#1990)
* Add AutoWIG to list of binding generators
2020-04-26 18:40:54 +02:00
Sebastian Koslowski a86ac538f5 rename args_kw_only to kwonly 2020-04-26 18:07:51 +02:00
Jason Rhinelander be0d804523 Support keyword-only arguments
This adds support for a `py::args_kw_only()` annotation that can be
specified between `py::arg` annotations to indicate that any following
arguments are keyword-only.  This allows you to write:

    m.def("f", [](int a, int b) { /* ... */ },
          py::arg("a"), py::args_kw_only(), py::arg("b"));

and have it work like Python 3's:

    def f(a, *, b):
        # ...

with respect to how `a` and `b` arguments are accepted (that is, `a` can
be positional or by keyword; `b` can only be specified by keyword).
2020-04-26 18:07:51 +02:00
Dustin Spicuzza 0dfffcf257 Add is_final to disallow inheritance from Python
- Not currently supported on PyPy
2020-04-26 09:46:44 +02:00
Orell Garten 9ed8b44033 Change __init__(self) to __new__(cls)
__init__(self) cannot return values. According to https://stackoverflow.com/questions/2491819/how-to-return-a-value-from-init-in-python __new__(cls) should be used, which works.
2020-04-26 09:21:42 +02:00
Axel Huebl 6ebfc4b2b0 Document CMAKE_CXX_STANDARD
This variable is a CMake community standard to set the C++
standard of a build. Document it in favor of the previous variable,
which stays as a legacy flag for existing projects.

https://cmake.org/cmake/help/v3.17/variable/CMAKE_CXX_STANDARD.html
2020-04-26 09:17:10 +02:00
Wenzel Jakob 0234871649 begin working on next version 2020-03-31 13:09:41 +02:00
Wenzel Jakob 3b1dbebabc v2.5.0 release 2020-03-31 13:00:39 +02:00
Eric Cousineau baf69345f6 Minor modifications to interrupt handling FAQ (#2007) 2019-11-25 22:14:06 +08:00
Charles Brossollet 0f1d3bfee2 Add FAQ entry for dealing with long functions interruption (#2000)
* Add FAQ entry, with code example, for dealing with long functions interruption
2019-11-25 17:59:53 +08:00
Francesco Biscani deb3cb238a Add exception translation for std::overflow_error. (#1977) 2019-11-14 08:56:58 +01:00
Erick Matsen b32b762c60 Fixing minor typo in basics.rst (#1984) 2019-11-14 08:54:46 +01:00
Wenzel Jakob dfde1554ea begin working on next version 2019-10-15 01:58:43 +02:00
Wenzel Jakob 80d452484c v2.4.3 release 2019-10-15 01:57:24 +02:00
Wenzel Jakob 34c2281e31 begin working on next version 2019-09-21 20:23:01 +02:00
Wenzel Jakob 2abd7e1eb4 updated release.rst to remove parts that are now automated 2019-09-21 20:22:33 +02:00
Wenzel Jakob 7ec2ddfc95 v2.4.2 release 2019-09-21 20:20:26 +02:00
Wenzel Jakob 82cf793588 begin working on next version 2019-09-20 11:12:22 +02:00
Wenzel Jakob e44fcc3c15 v2.4.1 release 2019-09-20 11:10:49 +02:00
Wenzel Jakob 5fd187ebe9 minor changelog cleanup
[ci skip]
2019-09-20 10:49:54 +02:00
Wenzel Jakob e825205ac6 begin working on v2.4.1 2019-09-19 23:18:04 +02:00
Wenzel Jakob 00a0aa9929 v2.4.0 release 2019-09-19 23:06:22 +02:00
Andre Schmeißer 19189b4c2c Make `overload_cast_impl` available in C++11 mode. (#1581)
* Make `overload_cast_impl` available in C++11 mode.

Narrow the scope of the `#if defined(PYBIND11_CPP14)` block around overload_cast to only
cover the parts where C++14 is stricly required. Thus, the implementation in
`pybind11::details::overload_cast_impl` is still available in C++11 mode.

* PR #1581: Modify test to use overload_cast_impl, update docs and change log
2019-08-19 12:54:33 +02:00
phil-zxx c6b699d9c2 Added ability to convert from datetime.date to system_clock::time_point (#1848)
* Added ability to convert from Python datetime.date and datetime.time to C++ system_clock::time_point
2019-07-19 11:28:48 +02:00
Ian Bell 502ffe50a9 Add docs and tests for unary op on class (#1814) 2019-06-22 12:07:41 +02:00
Wenzel Jakob 64f2a5f8e6 begin work on v2.3.1 2019-06-12 21:03:40 +02:00
Wenzel Jakob cf36e3d9ba updated changelog 2019-06-11 23:28:58 +02:00
Wenzel Jakob 51ca6b0832 Update docs on std::out_of_range exception mapping (#1254) 2019-06-11 23:28:58 +02:00
Chris Rusby 22859bb8fc Support more natural syntax for vector extend 2019-06-11 23:28:58 +02:00
Roland Dreier 7a24bcf1f6 Fix malformed reST (#1802)
Commit 2b045757b5 ("Improve documentation related to inheritance. (#1676)") left off
a ':' from a hyperlink, which breaks the Travis CI build.
2019-06-11 10:57:49 +02:00
Ivor Wanders 2b045757b5 Improve documentation related to inheritance. (#1676)
* Adds section to the reference.
* Adds section to advanced classes page describing how to use `get_overload`.
2019-06-10 22:12:28 +02:00
Manuel Schneider 492da592c2 another typo (#1675) 2019-06-10 22:05:12 +02:00
Darius Arnold 09330b94ea Fix typos in documentation (#1635)
* Always capitalize Eigen

* Fix spelling
2019-06-10 21:57:00 +02:00
Omar Awile ac6cb91a34 Fixed small typo (#1633)
I think this particular method binding should not be done with `PYBIND11_OVERLOAD_PURE` but instead `PYBIND11_OVERLOAD`.
2019-06-10 21:56:17 +02:00
Sergei Izmailov 979d75de23 doc: Add note about casting from `None` to `T*` (#1760)
* doc: Add note about casting from `None` to `T*`

* doc: reword 'none-to-pointer' note message

* doc: mention opaque types in 'none-to-pointer' note message
2019-06-10 21:03:17 +02:00
nstelzen c251434011 Added note in documentation regarding make install (#1801)
* Added note regarding make install
2019-06-10 16:35:36 +02:00
Wenzel Jakob 64205140bd added std::deque to overview.rst
[ci skip]
2018-11-16 06:46:48 +01:00
voxmea 17983e7425 Adds type_caster support for std::deque. (#1609)
* Adds std::deque to the types supported by list_caster in stl.h.
* Adds a new test_deque test in test_stl.{py,cpp}.
* Updates the documentation to include std::deque as a default
  supported type.
2018-11-16 06:45:19 +01:00
Ahuva Kroizer 8f5b7fce84 FAQ addition (#1606)
* Add possible solution to ImportError issue
2018-11-13 13:25:57 +01:00
Allan Leal e76dff7751 Fix for Issue #1258 (#1298)
* Fix for Issue #1258

list_caster::load method will now check for a Python string and prevent its automatic conversion to a list.
This should fix the issue "pybind11/stl.h converts string to vector<string> #1258" (https://github.com/pybind/pybind11/issues/1258)

* Added tests for fix of issue #1258

* Changelog: stl string auto-conversion
2018-10-11 10:28:12 +02:00
Semen Yesylevskyy ef13fb2e1c Info about inconsistent detection of Python version between pybind11 … (#1093)
* Info about inconsistent detection of Python version between pybind11 and CMake in FAQ
2018-09-12 00:20:56 +02:00
Wenzel Jakob f4245181ae enum_: move most functionality to a non-template implementation
This commit addresses an inefficiency in how enums are created in
pybind11. Most of the enum_<> implementation is completely generic --
however, being a template class, it ended up instantiating vast amounts
of essentially identical code in larger projects with many enums.

This commit introduces a generic non-templated helper class that is
compatible with any kind of enumeration. enum_ then becomes a thin
wrapper around this new class.

The new enum_<> API is designed to be 100% compatible with the old one.
2018-09-11 22:08:26 +02:00
Wenzel Jakob 35c82c7250 changelog for version 2.2.4 & features targeted for 2.3.0 2018-09-11 10:41:30 +02:00
Jeff VanOss 01839dce8d remove duplicate feature from list (#1476) 2018-09-11 10:39:17 +02:00
Axel Huebl 435dbdd114 add_module: allow include as SYSTEM (#1416)
pybind11 headers passed via the `pybind11_add_module` CMake
function can now be included as `SYSTEM` includes (`-isystem`).

This allows to set stricter (or experimental) warnings in
calling projects that might throw otherwise in headers
a user of pybind11 can not influence.
2018-08-29 13:20:11 +02:00
Wenzel Jakob d4b37a284a added py::ellipsis() method for slicing of multidimensional NumPy arrays
This PR adds a new py::ellipsis() method which can be used in
conjunction with NumPy's generalized slicing support. For instance,
the following is now valid (where "a" is a NumPy array):

py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];
2018-08-28 23:22:55 +02:00
Boris Dalstein b30734ee9f Fix typo in doc: build-in -> built-in 2018-07-17 11:28:15 -03:00
Thomas Hrabe 534b756cb3 Minor documentation clarification in numpy.rst (#1356) 2018-06-24 15:41:27 +02:00
Antony Lee 55dc131944 Clarify docs for functions taking bytes and not str. 2018-05-24 11:09:41 -03:00
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