Merge branch 'pybind:master' into master

This commit is contained in:
Steve R. Sun 2024-04-03 09:35:06 +08:00 committed by GitHub
commit 6ed90b7330
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 103 additions and 148 deletions

View File

@ -25,14 +25,14 @@ repos:
# Clang format the codebase automatically # Clang format the codebase automatically
- repo: https://github.com/pre-commit/mirrors-clang-format - repo: https://github.com/pre-commit/mirrors-clang-format
rev: "v17.0.6" rev: "v18.1.2"
hooks: hooks:
- id: clang-format - id: clang-format
types_or: [c++, c, cuda] types_or: [c++, c, cuda]
# Ruff, the Python auto-correcting linter/formatter written in Rust # Ruff, the Python auto-correcting linter/formatter written in Rust
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.2.0 rev: v0.3.5
hooks: hooks:
- id: ruff - id: ruff
args: ["--fix", "--show-fixes"] args: ["--fix", "--show-fixes"]
@ -40,13 +40,13 @@ repos:
# Check static types with mypy # Check static types with mypy
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.8.0" rev: "v1.9.0"
hooks: hooks:
- id: mypy - id: mypy
args: [] args: []
exclude: ^(tests|docs)/ exclude: ^(tests|docs)/
additional_dependencies: additional_dependencies:
- markdown-it-py<3 # Drop this together with dropping Python 3.7 support. - markdown-it-py
- nox - nox
- rich - rich
- types-setuptools - types-setuptools
@ -87,13 +87,13 @@ repos:
# Changes tabs to spaces # Changes tabs to spaces
- repo: https://github.com/Lucas-C/pre-commit-hooks - repo: https://github.com/Lucas-C/pre-commit-hooks
rev: "v1.5.4" rev: "v1.5.5"
hooks: hooks:
- id: remove-tabs - id: remove-tabs
# Avoid directional quotes # Avoid directional quotes
- repo: https://github.com/sirosen/texthooks - repo: https://github.com/sirosen/texthooks
rev: "0.6.4" rev: "0.6.6"
hooks: hooks:
- id: fix-ligatures - id: fix-ligatures
- id: fix-smartquotes - id: fix-smartquotes
@ -127,7 +127,7 @@ repos:
# Check for common shell mistakes # Check for common shell mistakes
- repo: https://github.com/shellcheck-py/shellcheck-py - repo: https://github.com/shellcheck-py/shellcheck-py
rev: "v0.9.0.6" rev: "v0.10.0.1"
hooks: hooks:
- id: shellcheck - id: shellcheck
@ -142,13 +142,13 @@ repos:
# PyLint has native support - not always usable, but works for us # PyLint has native support - not always usable, but works for us
- repo: https://github.com/PyCQA/pylint - repo: https://github.com/PyCQA/pylint
rev: "v3.0.3" rev: "v3.1.0"
hooks: hooks:
- id: pylint - id: pylint
files: ^pybind11 files: ^pybind11
- repo: https://github.com/python-jsonschema/check-jsonschema - repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.28.0 rev: 0.28.1
hooks: hooks:
- id: check-readthedocs - id: check-readthedocs
- id: check-github-workflows - id: check-github-workflows

View File

@ -925,8 +925,7 @@ using is_template_base_of
= decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)); = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
#else #else
struct is_template_base_of struct is_template_base_of
: decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) { : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)){};
};
#endif #endif
/// Check if T is an instantiation of the template `Class`. For example: /// Check if T is an instantiation of the template `Class`. For example:
@ -1108,14 +1107,14 @@ struct overload_cast_impl {
} }
template <typename Return, typename Class> template <typename Return, typename Class>
constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept constexpr auto operator()(Return (Class::*pmf)(Args...),
-> decltype(pmf) { std::false_type = {}) const noexcept -> decltype(pmf) {
return pmf; return pmf;
} }
template <typename Return, typename Class> template <typename Return, typename Class>
constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept constexpr auto operator()(Return (Class::*pmf)(Args...) const,
-> decltype(pmf) { std::true_type) const noexcept -> decltype(pmf) {
return pmf; return pmf;
} }
}; };

View File

@ -156,8 +156,9 @@ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args) {
} }
#else #else
template <size_t N, typename... Ts, typename... Args> template <size_t N, typename... Ts, typename... Args>
constexpr auto concat(const descr<N, Ts...> &d, const Args &...args) constexpr auto concat(const descr<N, Ts...> &d,
-> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) { const Args &...args) -> decltype(std::declval<descr<N + 2, Ts...>>()
+ concat(args...)) {
return d + const_name(", ") + concat(args...); return d + const_name(", ") + concat(args...);
} }
#endif #endif

View File

@ -318,13 +318,13 @@ struct type_info {
#define PYBIND11_INTERNALS_ID \ #define PYBIND11_INTERNALS_ID \
"__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \ "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB \
PYBIND11_BUILD_TYPE "__" PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
#define PYBIND11_MODULE_LOCAL_ID \ #define PYBIND11_MODULE_LOCAL_ID \
"__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \ "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB \
PYBIND11_BUILD_TYPE "__" PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__"
/// Each module locally stores a pointer to the `internals` data. The data /// Each module locally stores a pointer to the `internals` data. The data
/// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`. /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.

View File

@ -1184,14 +1184,14 @@ protected:
does not have a private operator new implementation. A comma operator is used in the does not have a private operator new implementation. A comma operator is used in the
decltype argument to apply SFINAE to the public copy/move constructors.*/ decltype argument to apply SFINAE to the public copy/move constructors.*/
template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>> template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
static auto make_copy_constructor(const T *) static auto make_copy_constructor(const T *) -> decltype(new T(std::declval<const T>()),
-> decltype(new T(std::declval<const T>()), Constructor{}) { Constructor{}) {
return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); }; return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
} }
template <typename T, typename = enable_if_t<is_move_constructible<T>::value>> template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>
static auto make_move_constructor(const T *) static auto make_move_constructor(const T *) -> decltype(new T(std::declval<T &&>()),
-> decltype(new T(std::declval<T &&>()), Constructor{}) { Constructor{}) {
return [](const void *arg) -> void * { return [](const void *arg) -> void * {
return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg)))); return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
}; };

View File

@ -158,8 +158,7 @@ void vector_modifiers(
return v.release(); return v.release();
})); }));
cl.def( cl.def("clear", [](Vector &v) { v.clear(); }, "Clear the contents");
"clear", [](Vector &v) { v.clear(); }, "Clear the contents");
cl.def( cl.def(
"extend", "extend",

View File

@ -353,7 +353,7 @@ CCompilerMethod = Callable[
distutils.ccompiler.CCompiler, distutils.ccompiler.CCompiler,
List[str], List[str],
Optional[str], Optional[str],
Optional[Union[Tuple[str], Tuple[str, Optional[str]]]], Optional[List[Union[Tuple[str], Tuple[str, Optional[str]]]]],
Optional[List[str]], Optional[List[str]],
bool, bool,
Optional[List[str]], Optional[List[str]],
@ -429,7 +429,7 @@ class ParallelCompile:
compiler: distutils.ccompiler.CCompiler, compiler: distutils.ccompiler.CCompiler,
sources: List[str], sources: List[str],
output_dir: Optional[str] = None, output_dir: Optional[str] = None,
macros: Optional[Union[Tuple[str], Tuple[str, Optional[str]]]] = None, macros: Optional[List[Union[Tuple[str], Tuple[str, Optional[str]]]]] = None,
include_dirs: Optional[List[str]] = None, include_dirs: Optional[List[str]] = None,
debug: bool = False, debug: bool = False,
extra_preargs: Optional[List[str]] = None, extra_preargs: Optional[List[str]] = None,

View File

@ -19,7 +19,7 @@ ignore = [
[tool.mypy] [tool.mypy]
files = ["pybind11"] files = ["pybind11"]
python_version = "3.7" python_version = "3.8"
strict = true strict = true
show_error_codes = true show_error_codes = true
enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"]

View File

@ -104,9 +104,8 @@ TEST_SUBMODULE(builtin_casters, m) {
m.def("good_utf16_string", [=]() { m.def("good_utf16_string", [=]() {
return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16}); return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16});
}); // b‽🎂𝐀z }); // b‽🎂𝐀z
m.def("good_utf32_string", [=]() { m.def("good_utf32_string",
return std::u32string({a32, mathbfA32, cake32, ib32, z32}); [=]() { return std::u32string({a32, mathbfA32, cake32, ib32, z32}); }); // a𝐀🎂‽z
}); // a𝐀🎂‽z
m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z
m.def("bad_utf8_string", []() { m.def("bad_utf8_string", []() {
return std::string("abc\xd0" return std::string("abc\xd0"
@ -117,9 +116,8 @@ TEST_SUBMODULE(builtin_casters, m) {
// UnicodeDecodeError // UnicodeDecodeError
m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); }); m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });
if (sizeof(wchar_t) == 2) { if (sizeof(wchar_t) == 2) {
m.def("bad_wchar_string", [=]() { m.def("bad_wchar_string",
return std::wstring({wchar_t(0x61), wchar_t(0xd800)}); [=]() { return std::wstring({wchar_t(0x61), wchar_t(0xd800)}); });
});
} }
m.def("u8_Z", []() -> char { return 'Z'; }); m.def("u8_Z", []() -> char { return 'Z'; });
m.def("u8_eacute", []() -> char { return '\xe9'; }); m.def("u8_eacute", []() -> char { return '\xe9'; });
@ -236,8 +234,7 @@ TEST_SUBMODULE(builtin_casters, m) {
// test_int_convert // test_int_convert
m.def("int_passthrough", [](int arg) { return arg; }); m.def("int_passthrough", [](int arg) { return arg; });
m.def( m.def("int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert());
"int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert());
// test_tuple // test_tuple
m.def( m.def(
@ -302,8 +299,7 @@ TEST_SUBMODULE(builtin_casters, m) {
// test_bool_caster // test_bool_caster
m.def("bool_passthrough", [](bool arg) { return arg; }); m.def("bool_passthrough", [](bool arg) { return arg; });
m.def( m.def("bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
"bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
// TODO: This should be disabled and fixed in future Intel compilers // TODO: This should be disabled and fixed in future Intel compilers
#if !defined(__INTEL_COMPILER) #if !defined(__INTEL_COMPILER)
@ -311,8 +307,7 @@ TEST_SUBMODULE(builtin_casters, m) {
// When compiled with the Intel compiler, this results in segmentation faults when importing // When compiled with the Intel compiler, this results in segmentation faults when importing
// the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when
// a newer version of icc is available. // a newer version of icc is available.
m.def( m.def("bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
"bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
#endif #endif
// test_reference_wrapper // test_reference_wrapper

View File

@ -63,10 +63,8 @@ TEST_SUBMODULE(call_policies, m) {
.def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>()) .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>())
.def_static("staticFunction", &Parent::staticFunction, py::keep_alive<1, 0>()); .def_static("staticFunction", &Parent::staticFunction, py::keep_alive<1, 0>());
m.def( m.def("free_function", [](Parent *, Child *) {}, py::keep_alive<1, 2>());
"free_function", [](Parent *, Child *) {}, py::keep_alive<1, 2>()); m.def("invalid_arg_index", [] {}, py::keep_alive<0, 1>());
m.def(
"invalid_arg_index", [] {}, py::keep_alive<0, 1>());
#if !defined(PYPY_VERSION) #if !defined(PYPY_VERSION)
// test_alive_gc // test_alive_gc

View File

@ -461,8 +461,7 @@ TEST_SUBMODULE(class_, m) {
py::class_<Nested>(base, "Nested") py::class_<Nested>(base, "Nested")
.def(py::init<>()) .def(py::init<>())
.def("fn", [](Nested &, int, NestBase &, Nested &) {}) .def("fn", [](Nested &, int, NestBase &, Nested &) {})
.def( .def("fa", [](Nested &, int, NestBase &, Nested &) {}, "a"_a, "b"_a, "c"_a);
"fa", [](Nested &, int, NestBase &, Nested &) {}, "a"_a, "b"_a, "c"_a);
base.def("g", [](NestBase &, Nested &) {}); base.def("g", [](NestBase &, Nested &) {});
base.def("h", []() { return NestBase(); }); base.def("h", []() { return NestBase(); });

View File

@ -289,8 +289,7 @@ TEST_SUBMODULE(copy_move_policies, m) {
"get_moveissue1", "get_moveissue1",
[](int i) { return std::unique_ptr<MoveIssue1>(new MoveIssue1(i)); }, [](int i) { return std::unique_ptr<MoveIssue1>(new MoveIssue1(i)); },
py::return_value_policy::move); py::return_value_policy::move);
m.def( m.def("get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
"get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
// Make sure that cast from pytype rvalue to other pytype works // Make sure that cast from pytype rvalue to other pytype works
m.def("get_pytype_rvalue_castissue", [](double i) { return py::float_(i).cast<py::int_>(); }); m.def("get_pytype_rvalue_castissue", [](double i) { return py::float_(i).cast<py::int_>(); });

View File

@ -185,14 +185,10 @@ TEST_SUBMODULE(custom_type_casters, m) {
py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg_v(nullptr, ArgInspector1()).noconvert(true),
py::arg() = ArgAlwaysConverts()); py::arg() = ArgAlwaysConverts());
m.def( m.def("floats_preferred", [](double f) { return 0.5 * f; }, "f"_a);
"floats_preferred", [](double f) { return 0.5 * f; }, "f"_a); m.def("floats_only", [](double f) { return 0.5 * f; }, "f"_a.noconvert());
m.def( m.def("ints_preferred", [](int i) { return i / 2; }, "i"_a);
"floats_only", [](double f) { return 0.5 * f; }, "f"_a.noconvert()); m.def("ints_only", [](int i) { return i / 2; }, "i"_a.noconvert());
m.def(
"ints_preferred", [](int i) { return i / 2; }, "i"_a);
m.def(
"ints_only", [](int i) { return i / 2; }, "i"_a.noconvert());
// test_custom_caster_destruction // test_custom_caster_destruction
// Test that `take_ownership` works on types with a custom type caster when given a pointer // Test that `take_ownership` works on types with a custom type caster when given a pointer

View File

@ -15,37 +15,26 @@ TEST_SUBMODULE(docstring_options, m) {
py::options options; py::options options;
options.disable_function_signatures(); options.disable_function_signatures();
m.def( m.def("test_function1", [](int, int) {}, py::arg("a"), py::arg("b"));
"test_function1", [](int, int) {}, py::arg("a"), py::arg("b")); m.def("test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
m.def(
"test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
m.def( m.def("test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring");
"test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring"); m.def("test_overloaded1", [](double) {}, py::arg("d"));
m.def(
"test_overloaded1", [](double) {}, py::arg("d"));
m.def( m.def("test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1");
"test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1"); m.def("test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2");
m.def(
"test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2");
m.def( m.def("test_overloaded3", [](int) {}, py::arg("i"));
"test_overloaded3", [](int) {}, py::arg("i")); m.def("test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr");
m.def(
"test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr");
options.enable_function_signatures(); options.enable_function_signatures();
m.def( m.def("test_function3", [](int, int) {}, py::arg("a"), py::arg("b"));
"test_function3", [](int, int) {}, py::arg("a"), py::arg("b")); m.def("test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
m.def(
"test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
options.disable_function_signatures().disable_user_defined_docstrings(); options.disable_function_signatures().disable_user_defined_docstrings();
m.def( m.def("test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
"test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
{ {
py::options nested_options; py::options nested_options;
@ -59,8 +48,7 @@ TEST_SUBMODULE(docstring_options, m) {
} }
} }
m.def( m.def("test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
"test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
{ {
py::options options; py::options options;

View File

@ -340,12 +340,10 @@ TEST_SUBMODULE(eigen_matrix, m) {
if (have_numpy) { if (have_numpy) {
py::module_::import("numpy"); py::module_::import("numpy");
Eigen::Matrix<double, 3, 3> defaultMatrix = Eigen::Matrix3d::Identity(); Eigen::Matrix<double, 3, 3> defaultMatrix = Eigen::Matrix3d::Identity();
m.def( m.def("defaults_mat", [](const Eigen::Matrix3d &) {}, py::arg("mat") = defaultMatrix);
"defaults_mat", [](const Eigen::Matrix3d &) {}, py::arg("mat") = defaultMatrix);
Eigen::VectorXd defaultVector = Eigen::VectorXd::Ones(32); Eigen::VectorXd defaultVector = Eigen::VectorXd::Ones(32);
m.def( m.def("defaults_vec", [](const Eigen::VectorXd &) {}, py::arg("vec") = defaultMatrix);
"defaults_vec", [](const Eigen::VectorXd &) {}, py::arg("vec") = defaultMatrix);
} }
// test_sparse, test_sparse_signature // test_sparse, test_sparse_signature
m.def("sparse_r", [mat]() -> SparseMatrixR { m.def("sparse_r", [mat]() -> SparseMatrixR {

View File

@ -121,8 +121,7 @@ void init_tensor_module(pybind11::module &m) {
[]() { return &get_fixed_tensor<Options>(); }, []() { return &get_fixed_tensor<Options>(); },
py::return_value_policy::copy); py::return_value_policy::copy);
m.def( m.def("copy_tensor", []() { return &get_tensor<Options>(); }, py::return_value_policy::copy);
"copy_tensor", []() { return &get_tensor<Options>(); }, py::return_value_policy::copy);
m.def( m.def(
"copy_const_tensor", "copy_const_tensor",

View File

@ -34,7 +34,7 @@ def test_captured_large_string(capsys):
def test_captured_utf8_2byte_offset0(capsys): def test_captured_utf8_2byte_offset0(capsys):
msg = "\u07FF" msg = "\u07ff"
msg = "" + msg * (1024 // len(msg) + 1) msg = "" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -44,7 +44,7 @@ def test_captured_utf8_2byte_offset0(capsys):
def test_captured_utf8_2byte_offset1(capsys): def test_captured_utf8_2byte_offset1(capsys):
msg = "\u07FF" msg = "\u07ff"
msg = "1" + msg * (1024 // len(msg) + 1) msg = "1" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -54,7 +54,7 @@ def test_captured_utf8_2byte_offset1(capsys):
def test_captured_utf8_3byte_offset0(capsys): def test_captured_utf8_3byte_offset0(capsys):
msg = "\uFFFF" msg = "\uffff"
msg = "" + msg * (1024 // len(msg) + 1) msg = "" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -64,7 +64,7 @@ def test_captured_utf8_3byte_offset0(capsys):
def test_captured_utf8_3byte_offset1(capsys): def test_captured_utf8_3byte_offset1(capsys):
msg = "\uFFFF" msg = "\uffff"
msg = "1" + msg * (1024 // len(msg) + 1) msg = "1" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -74,7 +74,7 @@ def test_captured_utf8_3byte_offset1(capsys):
def test_captured_utf8_3byte_offset2(capsys): def test_captured_utf8_3byte_offset2(capsys):
msg = "\uFFFF" msg = "\uffff"
msg = "12" + msg * (1024 // len(msg) + 1) msg = "12" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -84,7 +84,7 @@ def test_captured_utf8_3byte_offset2(capsys):
def test_captured_utf8_4byte_offset0(capsys): def test_captured_utf8_4byte_offset0(capsys):
msg = "\U0010FFFF" msg = "\U0010ffff"
msg = "" + msg * (1024 // len(msg) + 1) msg = "" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -94,7 +94,7 @@ def test_captured_utf8_4byte_offset0(capsys):
def test_captured_utf8_4byte_offset1(capsys): def test_captured_utf8_4byte_offset1(capsys):
msg = "\U0010FFFF" msg = "\U0010ffff"
msg = "1" + msg * (1024 // len(msg) + 1) msg = "1" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -104,7 +104,7 @@ def test_captured_utf8_4byte_offset1(capsys):
def test_captured_utf8_4byte_offset2(capsys): def test_captured_utf8_4byte_offset2(capsys):
msg = "\U0010FFFF" msg = "\U0010ffff"
msg = "12" + msg * (1024 // len(msg) + 1) msg = "12" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)
@ -114,7 +114,7 @@ def test_captured_utf8_4byte_offset2(capsys):
def test_captured_utf8_4byte_offset3(capsys): def test_captured_utf8_4byte_offset3(capsys):
msg = "\U0010FFFF" msg = "\U0010ffff"
msg = "123" + msg * (1024 // len(msg) + 1) msg = "123" + msg * (1024 // len(msg) + 1)
m.captured_output_default(msg) m.captured_output_default(msg)

View File

@ -22,8 +22,7 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
m.def("kw_func0", kw_func); m.def("kw_func0", kw_func);
m.def("kw_func1", kw_func, py::arg("x"), py::arg("y")); m.def("kw_func1", kw_func, py::arg("x"), py::arg("y"));
m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200); m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200);
m.def( m.def("kw_func3", [](const char *) {}, py::arg("data") = std::string("Hello world!"));
"kw_func3", [](const char *) {}, py::arg("data") = std::string("Hello world!"));
/* A fancier default argument */ /* A fancier default argument */
std::vector<int> list{{13, 17}}; std::vector<int> list{{13, 17}};
@ -79,14 +78,12 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
"kw_lb_func5", "kw_lb_func5",
[](const CustomRepr &) {}, [](const CustomRepr &) {},
py::arg("custom") = CustomRepr("array([[A, B],\r [C, D]])")); py::arg("custom") = CustomRepr("array([[A, B],\r [C, D]])"));
m.def( m.def("kw_lb_func6", [](const CustomRepr &) {}, py::arg("custom") = CustomRepr(" \v\t "));
"kw_lb_func6", [](const CustomRepr &) {}, py::arg("custom") = CustomRepr(" \v\t "));
m.def( m.def(
"kw_lb_func7", "kw_lb_func7",
[](const std::string &) {}, [](const std::string &) {},
py::arg("str_arg") = "First line.\n Second line."); py::arg("str_arg") = "First line.\n Second line.");
m.def( m.def("kw_lb_func8", [](const CustomRepr &) {}, py::arg("custom") = CustomRepr(""));
"kw_lb_func8", [](const CustomRepr &) {}, py::arg("custom") = CustomRepr(""));
// test_args_and_kwargs // test_args_and_kwargs
m.def("args_function", [](py::args args) -> py::tuple { m.def("args_function", [](py::args args) -> py::tuple {
@ -279,11 +276,9 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
// These should fail to compile: // These should fail to compile:
#ifdef PYBIND11_NEVER_DEFINED_EVER #ifdef PYBIND11_NEVER_DEFINED_EVER
// argument annotations are required when using kw_only // argument annotations are required when using kw_only
m.def( m.def("bad_kw_only1", [](int) {}, py::kw_only());
"bad_kw_only1", [](int) {}, py::kw_only());
// can't specify both `py::kw_only` and a `py::args` argument // can't specify both `py::kw_only` and a `py::args` argument
m.def( m.def("bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a);
"bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a);
#endif #endif
// test_function_signatures (along with most of the above) // test_function_signatures (along with most of the above)

View File

@ -374,8 +374,7 @@ TEST_SUBMODULE(methods_and_attributes, m) {
m.def("overload_order", [](const std::string &) { return 1; }); m.def("overload_order", [](const std::string &) { return 1; });
m.def("overload_order", [](const std::string &) { return 2; }); m.def("overload_order", [](const std::string &) { return 2; });
m.def("overload_order", [](int) { return 3; }); m.def("overload_order", [](int) { return 3; });
m.def( m.def("overload_order", [](int) { return 4; }, py::prepend{});
"overload_order", [](int) { return 4; }, py::prepend{});
#if !defined(PYPY_VERSION) #if !defined(PYPY_VERSION)
// test_dynamic_attributes // test_dynamic_attributes

View File

@ -287,8 +287,7 @@ TEST_SUBMODULE(numpy_array, sm) {
// [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works. // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
// Only accept the exact types: // Only accept the exact types:
sm.def( sm.def("overloaded3", [](const py::array_t<int> &) { return "int"; }, py::arg{}.noconvert());
"overloaded3", [](const py::array_t<int> &) { return "int"; }, py::arg{}.noconvert());
sm.def( sm.def(
"overloaded3", "overloaded3",
[](const py::array_t<double> &) { return "double"; }, [](const py::array_t<double> &) { return "double"; },
@ -444,9 +443,8 @@ TEST_SUBMODULE(numpy_array, sm) {
}); });
// resize to 3D array with each dimension = N // resize to 3D array with each dimension = N
sm.def("array_resize3", [](py::array_t<double> a, size_t N, bool refcheck) { sm.def("array_resize3",
a.resize({N, N, N}, refcheck); [](py::array_t<double> a, size_t N, bool refcheck) { a.resize({N, N, N}, refcheck); });
});
// test_array_create_and_resize // test_array_create_and_resize
// return 2D array with Nrows = Ncols = N // return 2D array with Nrows = Ncols = N
@ -460,9 +458,8 @@ TEST_SUBMODULE(numpy_array, sm) {
sm.def("array_view", sm.def("array_view",
[](py::array_t<uint8_t> a, const std::string &dtype) { return a.view(dtype); }); [](py::array_t<uint8_t> a, const std::string &dtype) { return a.view(dtype); });
sm.def("reshape_initializer_list", [](py::array_t<int> a, size_t N, size_t M, size_t O) { sm.def("reshape_initializer_list",
return a.reshape({N, M, O}); [](py::array_t<int> a, size_t N, size_t M, size_t O) { return a.reshape({N, M, O}); });
});
sm.def("reshape_tuple", [](py::array_t<int> a, const std::vector<int> &new_shape) { sm.def("reshape_tuple", [](py::array_t<int> a, const std::vector<int> &new_shape) {
return a.reshape(new_shape); return a.reshape(new_shape);
}); });
@ -471,8 +468,7 @@ TEST_SUBMODULE(numpy_array, sm) {
[](const py::array &a) { return a[py::make_tuple(0, py::ellipsis(), 0)]; }); [](const py::array &a) { return a[py::make_tuple(0, py::ellipsis(), 0)]; });
// test_argument_conversions // test_argument_conversions
sm.def( sm.def("accept_double", [](const py::array_t<double, 0> &) {}, py::arg("a"));
"accept_double", [](const py::array_t<double, 0> &) {}, py::arg("a"));
sm.def( sm.def(
"accept_double_forcecast", "accept_double_forcecast",
[](const py::array_t<double, py::array::forcecast> &) {}, [](const py::array_t<double, py::array::forcecast> &) {},
@ -493,8 +489,7 @@ TEST_SUBMODULE(numpy_array, sm) {
"accept_double_f_style_forcecast", "accept_double_f_style_forcecast",
[](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {}, [](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {},
py::arg("a")); py::arg("a"));
sm.def( sm.def("accept_double_noconvert", [](const py::array_t<double, 0> &) {}, "a"_a.noconvert());
"accept_double_noconvert", [](const py::array_t<double, 0> &) {}, "a"_a.noconvert());
sm.def( sm.def(
"accept_double_forcecast_noconvert", "accept_double_forcecast_noconvert",
[](const py::array_t<double, py::array::forcecast> &) {}, [](const py::array_t<double, py::array::forcecast> &) {},

View File

@ -77,9 +77,7 @@ def partial_nested_fmt():
partial_size = partial_ld_off + ld.itemsize partial_size = partial_ld_off + ld.itemsize
partial_end_padding = partial_size % np.dtype("uint64").alignment partial_end_padding = partial_size % np.dtype("uint64").alignment
partial_nested_size = partial_nested_off * 2 + partial_size + partial_end_padding partial_nested_size = partial_nested_off * 2 + partial_size + partial_end_padding
return "{{'names':['a'],'formats':[{}],'offsets':[{}],'itemsize':{}}}".format( return f"{{'names':['a'],'formats':[{partial_dtype_fmt()}],'offsets':[{partial_nested_off}],'itemsize':{partial_nested_size}}}"
partial_dtype_fmt(), partial_nested_off, partial_nested_size
)
def assert_equal(actual, expected_data, expected_dtype): def assert_equal(actual, expected_data, expected_dtype):

View File

@ -217,9 +217,8 @@ TEST_SUBMODULE(stl, m) {
// NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`), // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
// casters don't typically do anything with that, which means they fall to the `const Type &` // casters don't typically do anything with that, which means they fall to the `const Type &`
// caster. // caster.
m.def("cast_rv_map", []() { m.def("cast_rv_map",
return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; });
});
m.def("cast_rv_nested", []() { m.def("cast_rv_nested", []() {
std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v; std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
v.emplace_back(); // add an array v.emplace_back(); // add an array
@ -497,8 +496,7 @@ TEST_SUBMODULE(stl, m) {
}); });
// test_stl_pass_by_pointer // test_stl_pass_by_pointer
m.def( m.def("stl_pass_by_pointer", [](std::vector<int> *v) { return *v; }, "v"_a = nullptr);
"stl_pass_by_pointer", [](std::vector<int> *v) { return *v; }, "v"_a = nullptr);
// #1258: pybind11/stl.h converts string to vector<string> // #1258: pybind11/stl.h converts string to vector<string>
m.def("func_with_string_or_vector_string_arg_overload", m.def("func_with_string_or_vector_string_arg_overload",

View File

@ -270,7 +270,6 @@ TEST_SUBMODULE(stl_binders, m) {
PYBIND11_NUMPY_DTYPE(VStruct, w, x, y, z); PYBIND11_NUMPY_DTYPE(VStruct, w, x, y, z);
py::class_<VStruct>(m, "VStruct").def_readwrite("x", &VStruct::x); py::class_<VStruct>(m, "VStruct").def_readwrite("x", &VStruct::x);
py::bind_vector<std::vector<VStruct>>(m, "VectorStruct", py::buffer_protocol()); py::bind_vector<std::vector<VStruct>>(m, "VectorStruct", py::buffer_protocol());
m.def("get_vectorstruct", [] { m.def("get_vectorstruct",
return std::vector<VStruct>{{false, 5, 3.0, true}, {true, 30, -1e4, false}}; [] { return std::vector<VStruct>{{false, 5, 3.0, true}, {true, 30, -1e4, false}}; });
});
} }