Pybind11 2.13.1

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection.

Tags c++ python library embedded developers
License Public Domain
State initial

Recent Releases

2.13.101 Jul 2024 04:45 minor bugfix: New Features: Add support for `Typing.Callable ..., T `. `#5202 `_. : Avoid aligned allocation in free-threaded build in order to support macOS versions before 10.14. `#5200 `_.
2.13.026 Jun 2024 11:25 major bugfix: New Features: Support free-threaded CPython (3.13t). Add `py::mod_gil_not_used()` tag to indicate if a module supports running with the GIL disabled. `#5148 `_. Support for Python 3.6 was removed. (Official end-of-life: 2021-12-23). `#5177 `_. `py::list` gained a `.clear()` method. `#5153 `_. .. feat(types). Support for `type T ` was added to pybind11/typing.h. `#5166 `_. `Union` and `Optional` were added to `pybind11/typing.h`. `#5165 `_. .. feat(cmake). In CMake, if `PYBIND11_USE_CROSSCOMPILING` is enabled, then. `CMAKE_CROSSCOMPILING` will be respected and will keep pybind11 from accessing the interpreter during configuration. Several CMake variables will be required in this case, but can be deduced from the environment variable. `SETUPTOOLS_EXT_SUF`. The default (currently `OFF`) may be changed in the future. `#5083 `_. : A refcount (leading to heap-use-after-free) involving trampoline functions with `PyObject *` return type was. `#5156 `_. Return `py::ssize_t` from `.ref_count()` instead of `int`. `#5139 `_. A subtle involving C++ types with unusual `operator ` overrides was. `#5189 `_. Support Python 3.13 with minor, add to CI. `#5127 `_. .. (cmake). mistake affecting old cmake and old boost. `#5149 `_. Documentation: Build docs updated to feature scikit-build-core and meson-python, and updated setuptools instructions. `#5168 `_. Tests: Avoid immortal objects in tests. `#5150 `_. CI: Compile against Python 3.13t in CI. Use `macos-13` (Intel) for CI jobs for now (will drop Python 3.7 soon). `#5109 `_. Other: Some cleanup in preparation for 3.13 support. `#5137 `_. Avoid a warning by ensuring an iterator end check is included in release mode. `#5129 `_. Bump max cmake to 3.29. `#5075 `_. Update docs and noxfile. `#5071 `_.
2.12.028 Mar 2024 13:05 major bugfix: New Features: `pybind11` now supports compiling for. `NumPy 2 `_. Most code shouldn't change (see :ref:`upgrade-guide-2.12` for details). However, if you experience you can define `PYBIND11_NUMPY_1_ONLY` to disable the new support for now, but this will be removed in the future. `#5050 `_. `pybind11/gil_safe_call_once.h` was added (it needs to be included explicitly). The primary use case is GIL-safe initialization of C++. `static` variables. `#4877 `_. Support move-only iterators in `py::make_iterator`. `py::make_key_iterator`, `py::make_value_iterator`. `#4834 `_. Two simple `py::set_error()` functions were added and the documentation was updated accordingly. In particular, `py::exception::operator()` was deprecated (use one of the new functions instead). The documentation for. `py::exception` was further updated to not suggest code that may result in undefined behavior. `#4772 `_. : Removes potential for Undefined Behavior during process teardown. `#4897 `_. Improve compatibility with the nvcc compiler (especially CUDA 12.1/12.2). `#4893 `_. `pybind11/numpy.h` now imports NumPy's `multiarray` and `_internal` submodules with paths depending on the installed version of NumPy (for compatibility with NumPy 2). `#4857 `_. Builtins collections names in docstrings are now consistently rendered in lowercase (list, set, dict, tuple), in accordance with PEP 585. `#4833 `_. Added `py::typing::Iterator`, `py::typing::Iterable`. `#4832 `_. Render `py::function` as `Callable` in docstring. `#4829 `_. Also bump `PYBIND11_INTERNALS_VERSION` for MSVC, which unlocks two new features without creating additional incompatibilities. `#4819 `_. Guard against crashes/corruptions caused by modules built with different MSVC versions. `#4779 `_. A long-standing in the handling of Python multiple inheritance was. See PR #4762 for the rather complex details. `#4762 `_. `bind_map` with `using` declarations. `#4952 `_. Qualify `py::detail::concat` usage to avoid
2.11.101 Jan 2024 12:11 minor feature: Changes: * ``PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF`` is now provided as an option for disabling the default-on ``PyGILState_Check()``'s in ``pybind11::handle``'s ``inc_ref()`` ``dec_ref()``. `#4753 `_ * ``PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`` was disabled for PyPy in general (not just PyPy Windows). `#4751 `_
2.8.005 Oct 2021 03:16 minor feature: Added py::raise_from to enable chaining exceptions. #3215. Allow exception translators to be optionally registered local to a module instead of applying globally across all pybind11 modules. Use register_local_exception_translator(ExceptionTranslator translator) instead of register_exception_translator(ExceptionTranslator translator) to keep your exception remapping code local to the module. #2650. Add make_simple_namespace function for instantiating Python SimpleNamespace objects. #2840. pybind11::scoped_interpreter and initialize_interpreter have new arguments to allow sys.argv initialization. #2341. Allow Python builtins to be used as callbacks in CPython. #1413. Added view to view arrays with a different datatype. #987. Implemented reshape on arrays. #984. Enable defining custom __new__ methods on classes by ing preventing overriding methods if they have non-pybind11 siblings. #3265. Add make_value_iterator(), and make_key_iterator() to return references instead of copies. #3293. Improve the classes generated by bind_map: #3310 Change.items from an iterator to a dictionary view. Add.keys and.values (both dictionary views). Allow __contains__ to take any object. . Change.items from an iterator to a dictionary view. Add.keys and.values (both dictionary views). Allow __contains__ to take any object. pybind11::custom_type_setup was added, for customizing the PyHeapTypeObject corresponding to a class, which may be useful for enabling garbage collection support, among other things. #3287. Set __file__ constant when running eval_file in an embedded interpreter. #3233. Python objects and (C++17) std::optional now accepted in py::slice constructor. #1101. The pybind11 proxy types str, bytes, bytearray, tuple, list now consistently support passing ssize_t values for sizes and indexes. Previously, only size_t was accepted in several interfaces. #3219. Avoid evaluating PYBIND11_TLS_REPLACE_VALUE arguments more than once. #3290. enum value's __int__ returning non-int when
2.7.104 Aug 2021 03:16 minor feature: Allow Python builtins to be used as callbacks in CPython. #1413. regression in CMake Python package config: improper use of absolute path. #3144. Mingw64 and add to the CI testing matrix. #3132. Specified UTF8-encoding in calls of open(). #3137. Add clang-tidy-readability rules to make boolean casts explicit improving code readability. Also enabled other misc and readability clang-tidy checks. #3148. Move object in.pop() for list. #3116. Removed and warning suppressions. #3127 #3129 #3135 #3141 #3142 #3150 #3152 #3160 #3161.
2.7.017 Jul 2021 07:25 minor feature: Enable py::implicitly_convertible for py::class_-wrapped types. #3059. Allow function pointer extraction from overloaded functions. #2944. NumPy: added.char_() to type which gives the NumPy public char result, which also distinguishes types by bit length (unlike.kind()). #2864. Add pybind11::bytearray to manipulate bytearray similar to bytes. #2799. pybind11/stl/filesystem.h registers a type caster that, on C++17/Python 3.6+, converts std::filesystem::path to pathlib.Path and any os.PathLike to std::filesystem::path. #2730. A PYBIND11_VERSION_HEX define was added, similar to PY_VERSION_HEX. #3120. py::str changed to exclusively hold PyUnicodeObject. Previously py::str could also hold bytes, which is probably surprising, was never documented, and can mask (e.g. accidental use of py::str instead of py::bytes). #2409. Add a safety guard to ensure that the Python GIL is held when C++ calls back into Python via object_api::operator() (e.g. py::function __call__). (This feature is available for Python 3.6+ only.) #2919. Catch a missing self argument in calls to __init__(). #2914. Use std::string_view if available to avoid a copy when passing an object to a std::ostream. #3042. An important warning about thread safety was added to the iostream.h documentation; attempts to make py::scoped_ostream_redirect thread safe have been removed, as it was only partially effective. #2995. Performance: avoid unnecessary strlen calls. #3058. auto-generated documentation string when using const T in pyarray_t. #3020. Unify error messages thrown by simple_collector/unpacking_collector. #3013. pybind11::builtin_exception is now explicitly exported, which means the types included/defined in different modules are identical, and exceptions raised in different modules can be caught correctly. The documentation was updated to explain that custom exceptions that are used across module boundaries need to be explicitly exported as well. #2999. exception when printing UTF-8 to a scoped_ostream_r
2.6.227 Jan 2021 06:05 minor feature: enum: add missing Enum.value property. #2739. Allow thread termination to be avoided during shutdown for CPython 3.7+ via.disarm for gil_scoped_acquire/gil_scoped_release. #2657. where the constructor of object subclasses would not throw on being passed a Python object of the wrong type. #2701. The type_caster for integers does not convert Python objects with __int__ anymore with noconvert or during the first round of trying overloads. #2698. When casting to a C++ integer, __index__ is always called and not considered as conversion, consistent with Python 3.8+. #2801. Setup helpers: extra_compile_args and extra_link_args automatically set by Pybind11Extension are now prepended, which allows them to be overridden by user-set extra_compile_args and extra_link_args. #2808. Setup helpers: Don't trigger unused parameter warning. #2735. CMake: Support running with --warn-uninitialized active. #2806. CMake: Avoid error if included from two submodule directories. #2804. CMake: STATIC / SHARED being ignored in FindPython mode. #2796. CMake: Respect the setting for CMAKE_CXX_VISIBILITY_PRESET if defined. #2793. CMake: with FindPython2/FindPython3 not working with pybind11::embed. #2662. CMake: mixing local and installed pybind11's would prioritize the installed one over the local one (regression in 2.6.0). #2716. segfault in multithreaded environments when using scoped_ostream_redirect. #2675. Leave docstring unset when all docstring-related options are disabled, rather than set an empty string. #2745. The module key in builtins that pybind11 uses to store its internals changed from std::string to a python str type (more natural on Python 2, no change on Python 3). #2814. assertion error related to unhandled (later overwritten) exception in CPython 3.8 and 3.9 debuilds. #2685. py::gil_scoped_acquire assert with CPython 3.9 debuild. #2683. with a test failing on PyTest 6.2. #2741. warning modifying constructor parameter 'flag' that shadows a field of 'set_flag'
2.6.112 Nov 2020 03:15 minor feature: py::exec, py::eval, and py::eval_file now add the builtins module as "__builtins__" to their globals argument, better matching exec and eval in pure Python. #2616. setup_helpers will no longer set a minimum macOS version lower than the current version. #2622. Allow deleting static properties. #2629. Seal a leak in def_buffer, cleaning up the capture object after the class_ object goes out of scope.#2634. pybind11_INCLUDE_DIRS was incorrect, potentially causing a regression if it was expected to include PYTHON_INCLUDE_DIRS (please use targets instead). #2636. Added parameter names to the py::enum_ constructor and methods, avoiding arg0 in the generated docstrings. #2637. Added needs_recompile optional function to the ParallelCompiler helper, to allow a recompile to be skipped based on a user-defined function. #2643.
2.6.022 Oct 2020 15:05 minor feature: Keyword-only arguments supported in Python 2 or 3 with py::kw_only(). #2100. Positional-only arguments supported in Python 2 or 3 with py::pos_only(). #2459. py::is_final() class modifier to block subclassing (CPython only). #2151. Added py::prepend(), allowing a function to be placed at the beginning of the overload chain. #1131. Access to the type object now provided with py::type::of() and py::type::of(h). #2364. Perfect forwarding support for methods. #2048. Added py::error_already_set::discard_as_unraisable(). #2372. py::hash is now public. #2217. py::class_ is now supported. Note that writing to one data member of the union and reading another (type punning) is UB in C++. Thus pybind11-bound enums should never be used for such conversions. #2320. Classes now check local scope when registering members, allowing a subclass to have a member with the same name as a parent (such as an enum). #2335. Error now thrown when __init__ is forgotten on subclasses. #2152. Throw error if conversion to a pybind11 type if the Python object isn't a valid instance of that type, such as py::bytes(o) when py::object o isn't a bytes instance. #2349. Throw if conversion to str fails. #2477. py::module was renamed py::module_ to avoid with C++20 when used unqualified, but an alias py::module is provided for backward compatibility. #2489. Public constructors for py::module_ have been deprecated; please use pybind11::module_::create_extension_module if you were using the public constructor (fairly rare after PYBIND11_MODULE was introduced). #2552. PYBIND11_OVERLOAD macros and get_overload function replaced by correctly-named PYBIND11_OVERRIDE and get_override, ing inconsistencies in the presence of a closing ; in these macros. get_type_overload is deprecated. #2325. The Python package was reworked to be more powerful and useful. #2433 build-setuptools is easier thanks to a new pybind11.setup_helpers module, which provides utilities to use setuptools with pybind11. It c
2.6.0rc111 Oct 2020 07:25 minor feature: ci: publish in two steps . Check if module file extension could be queried correctly. . Moving tp_class access, and consistent fully-qualified naming for PyP . . Allow raw unions without base classes in is_accessible_base_of. . : conda-forge patch. . Unify Python 2 3 py::module constructor, and make contructor with p . . Feat: parallel compiler. . /Check actual value when deregistering pybind11 instance. . Add unchecked_reference::operator() and operator to overload resolu . . Feat: vectorize functions with void return type. . ci: label PRs with changelog needed. . Update pr_merged.yml. . : ensure the GIL is held when copying a function.. . ci: labeler. . Refactor: import check as a common function. . Docs: odd spacing. . Refactor: module - module_ with typedef. . Buffer_info for ctypes buffers. . Docs: add std::valarray to docs/advanced/cast/stl.rst. . Chore: drop support for PyPy 7.3.1 and clean up old PyPy workarounds (. . : find_import didn't work properly for classic tools. . Fail on passing py::object with wrong Python type to py::object subcl . . Feat: py::prepend tag. . : PYBIND11_OBJECT required pybind11 namespace (regression). . Docs: minor cleanup. . ci: test on Windows 3.8 and 3.9 (mostly). . Docs: use sorted(glob()) in example . Test: hide segfault. . Check scope's __dict__ instead of using hasattr when registering clas . . Feat: deprecate public constructors of module_ class. . Docs: known. . ci: update PGI to 20.9. . : do not use abi::__forced_unwind with libc++, even with gcc inste . . ci: labeler. . Chore: bump to 2.6.0rc1. . : formatting. Refactor: simpler followup to #2569. . : allow cmake varibles from Python calls to be cached.
2.6.0b103 Oct 2020 10:45 minor feature: Begin working on next version . Allows users to specialize polymorphic_type_hook with std::enable_if. . Adding a default virtual destructor to Animal type in test_tagbased_p . . Utilize CMake's language standards abstraction when possible. . Document CMAKE_CXX_STANDARD. . Declare `operator==` and `operator!=` member functions const. . Change __init__(self) to __new__(cls). . Find library path to via glob command in /usr/lib/llvm- . . Change set_path to set_file. . Typo in sorted function call argument reverse. . Add is_final to disallow inheritance from Python. . Compilation with clang-cl. . Support keyword-only arguments. . Rename args_kw_only to kwonly. . Adding method names to cpp_function constructor calls in enum_base. . Propagate exceptions in sequence::size(). . Add AutoWIG to list of binding generators. . Revert "Change __init__(self) to __new__(cls)". . CI, prepare test on Python 3.9 beta. . Pytypes.h: docs generation. . Cmake: Expose `PYBIND11_TEST_OVERRIDE`. . Operators: Move hash check to before mutations, tweak whitespace. . Operators: Explicitly expose `py::hash(py::self)`. . Disable defining (v)snprintf as macro in modern Visual Studio. . common.h Mark entry point as "unused". . Compiler error with MSVC 17 and CUDA 10.2. . common.h Mark another entry point as "unused". . Deepcopy documentation. . Add lvalue ref-qualified cpp_function constructors. . Render full numpy numeric names (e.g. numpy.int32). . Render py::iterator/py::iterable as Iterator/Iterable in docstrings. . Render pybind11::array as numpy.ndarray in docstrings. . Render `py::int_` as `int` in docstrings. . Test py::iterable/py::iterator representation in docstrings. . Setuptools record of headers. . Docs typo. . Ignore another type of visual studio project file. . Render `py::none` as `None` in docstrings. . Add failing optional test. . Optional dereference type deduction. . Compile error on GCC4.8. . Add additiona
2.5.001 Apr 2020 22:25 minor feature: begin working on next version . build with -Wmissing-prototypes. . misleading comment corrected (strides in buffer_info is bytes and not . . Obey __cpp_sized_deallocation and __cpp_aligned_new. . make builds with python tests and cpp tests fail if either one fails (# . . Report type names in return value policy-related cast exceptions. . test pair-copyability on C++17 upwards. . CMake: Add Python 3.8 to pybind11Tools. . Prevent cmake error when preempty. . ing minor typo in basics.rst. . ing SystemError when nb_bool/nb_nonzero sets a Python exception in . . Add exception translation for std::overflow_error.. . Aligned allocation for clang-cl. . support for readonly buffers. . Add FAQ entry for dealing with long functions interruption. . Minor modifications to interrupt handling FAQ. . numpy.h: minor preprocessor suggested by @chaekwan. . Revert "numpy.h: minor preprocessor suggested by @chaekwan". . Install headers using both headers and package_data. . Pin breathe to 4.13.1. . Use newer macOS image for python3 testing. . a memory leak when creating Python3 modules.. . Revert "a memory leak when creating Python3 modules. ". . Free tstate on python 3.7+ on finalize_interpreter. . undo #define copysign in pyconfig.h. . : Handle deinterpreter. . Add C++20 char8_t/u8string support. . Use C++17 fold expressions when casting tuples and argument lists (#2043. . Travis CI (MacOS, Py3). . bindings for import_error exception. . Handle cases where binding code immediately throws py::error_already_set. . Declare call_impl() as . . compilation with MinGW only. . stl_bind: add binding for std::vector::clear. . the use of MSVC in an MSYS environment. . pybind11Tools.cmake: search for Python 3.9. . v2.5.0 release.
2.4.315 Oct 2019 15:45 minor feature: Updated release.rst to remove parts that are now automated . Begin working on next version. . Version mismatch typos in.travis.yml. . Adapt to python3.8 C API change. . v2.4.3 release.
2.4.225 Sep 2019 06:45 minor feature: Begin working on next version . Future-proof Python version check from commit 31680e6. . Remove usage of C++14 constructs. . v2.4.2 release.
2.4.020 Sep 2019 19:25 minor feature: begin work on v2.3.1 . added several folks who've made repeated contributions. . casting of time points with non-system-clock duration with VS (#1748. . (warning about redefined macros). . Add docs and tests for unary op on class. . error_already_set: acquire GIL one line earlier. . test suite (pytest changes in ExceptionInfo class). . Replace a usage of C++14 language features with C++11 code. . Dtype field ordering for NumPy 1.14. . quiet clang warning by adding default move ctor. . Make sure `detail::get_internals` acquires the GIL before making Pyth . . renamed local gil_scoped_acquire to gil_scoped_acquire_local to avoid . . Allow Windows.h min/max to coexist with pybind11. . Add support for __await__, __aiter__, and __anext__ protocols. . Added ability to convert from to system_clock::time_poi . . numpy: Add test for explicit dtype checks. At present, int64 + uint64 . . numpy: Provide concrete size aliases. . numpy: refcount leak to dtype singleton. . add mingw compatibility. . In internals.h, only look at _DEwhen compiling with MSVC.. . Avoid use of lambda to work around a clang.. . Add negative indexing support to stl_bind.. . -Wmissing-prototypes warning on Clang.. . Added set::contains and generalized dict::contains. . Added.empty() to all collection types. . Detect whether we are running in a Conda environment and adjust get_i . . Expose BufferError among other pybind11 exceptions.. . Make `overload_cast_impl` available in C++11 mode.. . Added support for list insertion.. . Don't strip desymbols in RelWithDebInfo mode. . Add const to buffer:request(). . restores __invert__ to arithmetic-enabled enum. Avoid conversion to `int_` rhs argument of enum eq/ne. . pybind11 internals: separate different compilers. . Avoid infinite recursion in is_copy_constructible. . v2.4.0 release.
2.3.004 Jul 2019 14:25 minor feature: updated changelog for v2.2.1 release . Make it possible to generate constexpr signatures in C++11 mode. . Use semi-constexpr signatures on MSVC. . Simplify function signature annotation and parsing. . dtype string leak. . Remove superfluous "requires_numpy". . correct stride in matrix example and test. . Specify minimum needed cmake version in test suite. . some minor mistakes in comments on struct instance. . Upgrading to Xcode 9 OSX/Py3 build failure. . `char ` arguments being non-bindable. . Add informative compilation failure for method_adaptor failures. . D Nx1/1xN inputs to eigen dense vector args. . Build /permissive- under VS2017. . Miscellaneous travis-ci updates/. Qualify `cast_op_type` to help ICC. . new flake8 E741 error from using `l` variable. . Trivial typos. . __qualname__ and nested class naming. . Added write only property functions for. support docstrings in enum::value(). . added citation reference. . Moved section on licensing of contributions. . Add -Wdeprecated to test suite and associated warnings. . Clean up eigen download code (and bump to 3.3.4). . Document using atexit for module destructors on PyPy. . Matching Python 2 int behavior on Python 2. . Remove spurious quote in error message.. . Silence new MSVC C++17 deprecation warnings. . Update PyPI URLs. . premature destruction of args/kwargs arguments. . leak in var arg handling. . Simplify arg copying. . Added py::args ref counting tests. . Make register_dtype() accept any field containers. . Add spaces around "=" in signature repr. . for numpy 1.14.0 compatibility. . Use a named rather than anon struct in instance. . misc. typos. . return from std::map bindings to __delitem__. . segfault when reloading interpreter with external modules. . Use stricter brace initialization. . Remove unnecessary `detail::`. . MSVC workaround for broken `using detail::_` warning. . pybind11 interoperability with Clang trunk. . added v2.2.2 changelog. . numpy
2.2.405 Feb 2019 12:09 minor bugfix: Use new Python 3.7 Thread Specific Storage (TSS) implementation if available. #1454, #1517. Fixes for newer MSVC versions and C++17 mode. #1347, #1462. Propagate return value policies to type-specific casters when casting STL containers. #1455. Allow ostream-redirection of more than 1024 characters. #1479. Set Py_DEBUG define when compiling against a debug Python build. #1438. Untangle integer logic in number type caster to work for custom types that may only be castable to a restricted set of builtin types. #1442. CMake build system: Remember Python version in cache file. #1434. Fix for custom smart pointers: use std::addressof to obtain holder address instead of operator . #1435. Properly report exceptions thrown during module initialization. #1362. Fixed a segmentation fault when creating empty-shaped NumPy array. #1371. The version of Intel C++ compiler must be = 2017, and this is now checked by the header files. #1363. A few minor typo fixes and improvements to the test suite, and patches that silence compiler warnings.