Compare commits

...

11 Commits

Author SHA1 Message Date
Tom de Geus e1dd502ed0
Merge a14c936562 into 1f8b4a7f1a 2024-09-20 23:44:18 -07:00
Hintay 1f8b4a7f1a
fix(cmake): `NO_EXTRAS` in `pybind11_add_module` function partially working (#5378) 2024-09-19 11:24:35 -04:00
dependabot[bot] ad9fd39e14
chore(deps): bump pypa/cibuildwheel in the actions group (#5376)
Bumps the actions group with 1 update: [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel).


Updates `pypa/cibuildwheel` from 2.20 to 2.21
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.20...v2.21)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-17 10:19:17 -07:00
vfdev 1d9483ff73
Added exception translator specific mutex used with try_translate_exceptions (#5362)
* Added exception translator specific mutex used with try_translate_exceptions
Fixes #5346

* - Replaced with_internals_for_exception_translator by with_exception_translators
- Incremented PYBIND11_INTERNALS_VERSION
- Added a test

* style: pre-commit fixes

* Fixed formatting and added explicit to ctors

* Addressed PR review comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-09-17 09:47:20 -07:00
Tom de Geus a14c936562
Update tests/test_make_alias.py
Co-authored-by: Sebastian Koslowski <sebastian.koslowski@gmail.com>
2022-02-26 22:37:44 +01:00
Tom de Geus eb2ecf1033
Update tests/test_make_alias.cpp
Co-authored-by: Sebastian Koslowski <sebastian.koslowski@gmail.com>
2022-02-26 22:37:31 +01:00
Tom de Geus 549f3b7e54
Update include/pybind11/pybind11.h
Co-authored-by: Sebastian Koslowski <sebastian.koslowski@gmail.com>
2022-02-26 22:37:05 +01:00
Tom de Geus f4ee39c229
Addressing compiler errors 2022-02-26 16:57:15 +01:00
Tom de Geus 726918d74a
Fixing compiler errors 2022-02-26 16:52:00 +01:00
pre-commit-ci[bot] ae3cfa82cc [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2022-02-26 15:45:53 +00:00
Tom de Geus 9c8df99e40
Adding "make_alias" to use a different `__name__` as shared-object 2022-02-26 16:43:38 +01:00
10 changed files with 143 additions and 26 deletions

View File

@ -22,7 +22,7 @@ jobs:
submodules: true
fetch-depth: 0
- uses: pypa/cibuildwheel@v2.20
- uses: pypa/cibuildwheel@v2.21
env:
PYODIDE_BUILD_EXPORTS: whole_archive
with:

View File

@ -50,17 +50,17 @@ inline void try_translate_exceptions() {
- delegate translation to the next translator by throwing a new type of exception.
*/
bool handled = with_internals([&](internals &internals) {
auto &local_exception_translators = get_local_internals().registered_exception_translators;
if (detail::apply_exception_translators(local_exception_translators)) {
return true;
}
auto &exception_translators = internals.registered_exception_translators;
if (detail::apply_exception_translators(exception_translators)) {
return true;
}
return false;
});
bool handled = with_exception_translators(
[&](std::forward_list<ExceptionTranslator> &exception_translators,
std::forward_list<ExceptionTranslator> &local_exception_translators) {
if (detail::apply_exception_translators(local_exception_translators)) {
return true;
}
if (detail::apply_exception_translators(exception_translators)) {
return true;
}
return false;
});
if (!handled) {
set_error(PyExc_SystemError, "Exception escaped from default exception translator!");

View File

@ -39,7 +39,11 @@
# if PY_VERSION_HEX >= 0x030C0000 || defined(_MSC_VER)
// Version bump for Python 3.12+, before first 3.12 beta release.
// Version bump for MSVC piggy-backed on PR #4779. See comments there.
# define PYBIND11_INTERNALS_VERSION 5
# ifdef Py_GIL_DISABLED
# define PYBIND11_INTERNALS_VERSION 6
# else
# define PYBIND11_INTERNALS_VERSION 5
# endif
# else
# define PYBIND11_INTERNALS_VERSION 4
# endif
@ -177,6 +181,7 @@ static_assert(sizeof(instance_map_shard) % 64 == 0,
struct internals {
#ifdef Py_GIL_DISABLED
pymutex mutex;
pymutex exception_translator_mutex;
#endif
// std::type_index -> pybind11's type information
type_map<type_info *> registered_types_cpp;
@ -643,6 +648,19 @@ inline auto with_internals(const F &cb) -> decltype(cb(get_internals())) {
return cb(internals);
}
template <typename F>
inline auto with_exception_translators(const F &cb)
-> decltype(cb(get_internals().registered_exception_translators,
get_local_internals().registered_exception_translators)) {
auto &internals = get_internals();
#ifdef Py_GIL_DISABLED
std::unique_lock<pymutex> lock((internals).exception_translator_mutex);
#endif
auto &local_internals = get_local_internals();
return cb(internals.registered_exception_translators,
local_internals.registered_exception_translators);
}
inline std::uint64_t mix64(std::uint64_t z) {
// David Stafford's variant 13 of the MurmurHash3 finalizer popularized
// by the SplitMix PRNG.

View File

@ -1301,6 +1301,21 @@ public:
// For Python 2, reinterpret_borrow was correct.
return reinterpret_borrow<module_>(m);
}
struct strip_leading_underscore_from_name {};
module_ make_alias(const char *name) {
module_ ret = *this;
ret.attr("__name__") = name;
return ret;
}
module_ make_alias(strip_leading_underscore_from_name) {
const char *name = PyModule_GetName(*this);
if (name && name[0] == '_')
name += 1;
return make_alias(name);
}
};
PYBIND11_NAMESPACE_BEGIN(detail)
@ -2586,10 +2601,12 @@ void implicitly_convertible() {
}
inline void register_exception_translator(ExceptionTranslator &&translator) {
detail::with_internals([&](detail::internals &internals) {
internals.registered_exception_translators.push_front(
std::forward<ExceptionTranslator>(translator));
});
detail::with_exception_translators(
[&](std::forward_list<ExceptionTranslator> &exception_translators,
std::forward_list<ExceptionTranslator> &local_exception_translators) {
(void) local_exception_translators;
exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
});
}
/**
@ -2599,11 +2616,12 @@ inline void register_exception_translator(ExceptionTranslator &&translator) {
* the exception.
*/
inline void register_local_exception_translator(ExceptionTranslator &&translator) {
detail::with_internals([&](detail::internals &internals) {
(void) internals;
detail::get_local_internals().registered_exception_translators.push_front(
std::forward<ExceptionTranslator>(translator));
});
detail::with_exception_translators(
[&](std::forward_list<ExceptionTranslator> &exception_translators,
std::forward_list<ExceptionTranslator> &local_exception_translators) {
(void) exception_translators;
local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
});
}
/**

View File

@ -0,0 +1,10 @@
from __future__ import annotations
class PythonMyException7(Exception):
def __init__(self, message):
self.message = message
super().__init__(message)
def __str__(self):
return "[PythonMyException7]: " + self.message.a

View File

@ -111,6 +111,16 @@ struct PythonAlreadySetInDestructor {
py::str s;
};
struct CustomData {
explicit CustomData(const std::string &a) : a(a) {}
std::string a;
};
struct MyException7 {
explicit MyException7(const CustomData &message) : message(message) {}
CustomData message;
};
TEST_SUBMODULE(exceptions, m) {
m.def("throw_std_exception",
[]() { throw std::runtime_error("This exception was intentionally thrown."); });
@ -385,4 +395,33 @@ TEST_SUBMODULE(exceptions, m) {
// m.def("pass_exception_void", [](const py::exception<void>&) {}); // Does not compile.
m.def("return_exception_void", []() { return py::exception<void>(); });
m.def("throws7", []() {
auto data = CustomData("abc");
throw MyException7(data);
});
py::class_<CustomData>(m, "CustomData", py::module_local())
.def(py::init<const std::string &>())
.def_readwrite("a", &CustomData::a);
PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object>
PythonMyException7_storage;
PythonMyException7_storage.call_once_and_store_result([&]() {
auto mod = py::module_::import("custom_exceptions");
py::object obj = mod.attr("PythonMyException7");
return obj;
});
py::register_local_exception_translator([](std::exception_ptr p) {
try {
if (p) {
std::rethrow_exception(p);
}
} catch (const MyException7 &e) {
auto exc_type = PythonMyException7_storage.get_stored();
py::object exc_inst = exc_type(e.message);
PyErr_SetObject(PyExc_Exception, exc_inst.ptr());
}
});
}

View File

@ -3,6 +3,7 @@ from __future__ import annotations
import sys
import pytest
from custom_exceptions import PythonMyException7
import env
import pybind11_cross_module_tests as cm
@ -195,6 +196,10 @@ def test_custom(msg):
raise RuntimeError("Exception error: caught child from parent") from err
assert msg(excinfo.value) == "this is a helper-defined translated exception"
with pytest.raises(PythonMyException7) as excinfo:
m.throws7()
assert msg(excinfo.value) == "[PythonMyException7]: abc"
def test_nested_throws(capture):
"""Tests nested (e.g. C++ -> Python -> C++) exception handling"""

22
tests/test_make_alias.cpp Normal file
View File

@ -0,0 +1,22 @@
/*
tests/make_alias -- make alias
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include <pybind11/pybind11.h>
#include "constructor_stats.h"
#include "pybind11_tests.h"
#if defined(_MSC_VER)
# pragma warning(disable : 4996) // C4996: std::unary_negation is deprecated
#endif
TEST_SUBMODULE(_make_alias, m) {
ma = m.make_alias(pybind11::module::strip_leading_underscore_from_name{});
ma.def("foo", []() -> {});
}

9
tests/test_make_alias.py Normal file
View File

@ -0,0 +1,9 @@
import pytest
from pybind11_tests import ConstructorStats
m = pytest.importorskip("pybind11_tests._make_alias")
def assert_name(mat):
assert m.__name__ == "make_alias"

View File

@ -274,10 +274,6 @@ function(pybind11_add_module target_name)
target_link_libraries(${target_name} PRIVATE pybind11::embed)
endif()
if(MSVC)
target_link_libraries(${target_name} PRIVATE pybind11::windows_extras)
endif()
# -fvisibility=hidden is required to allow multiple modules compiled against
# different pybind versions to work properly, and for some features (e.g.
# py::module_local). We force it on everything inside the `pybind11`